how to override a validation call in activerecord in a gem?
I am using apn_on_rails for iphone push notification with rails.
Right now, the validation on token is no longer valid because the validation requires a space every 8 characters: validates_format_of :token, :with => /^[a-z0-9]{8}\s[a-z0-9]{8}\s[a-z0-9]{8}\s[a-z0-9]{8}\s[a-z0-9]{8}\s[a-z0-9]{8}\s[a-z0-9]{8}\s[a-z0-9]{8}$/
http://github.com/markbates/apn_on_rails/blob/master/lib/apn_on_rails/app/models/apn/device.rb
But the device token I got from Objective-C has no space.
So I'd like to override the validation to make it: validates_format_of :token, :with => /^[a-z0-9]{64}$/
how can I do it without modifying the source inside t开发者_运维问答he gem?
Thanks.
Or make the code validate:
[56, 48, 40, 32, 24, 16, 8].each { |i| code.insert(i, ' ') }
The metaprogramming example is great but you can easily end up breaking code that depends on this validation. What I would recommend is writing your own accessor methods that modify the attribute to work with your gem. For example, use wesgarrison's code and modify the setter:
def token= token
@token = [56, 48, 40, 32, 24, 16, 8].each { |i| token.insert(i, ' ') }
end
You could then add this code to a wrapper module or a child class that you use in your code.
You're not the first with this issue - I found the following article called Removing Rails validations with metaprogramming helpful.
精彩评论