Reputation: 2390
I'm trying to write my first gem, which has validations for credit card fields. I've created a module MyCcValidation
and the following works:
class User < ActiveRecord::Base
include MyCcValidation
my_validation_helper { some_data }
end
What I hope to achieve is to be able to add the gem to my Gemfile
and have my_validation_helper
available "out of the box". I tried many ways of extending ActiveModel::Validations
but no luck so far. It's my first gem so I'm probably missing something since e.g. devise
seems to have no problems with it. How this should be done?
Upvotes: 3
Views: 197
Reputation: 46
Extending ActiveModel::Validations
directly does not sound like a good idea. Try to define a custom validator class with, then reopen the ActiveModel::Validations::HelperMethods
module and add your_validation_helper
there.
Example:
class MyCustomValidator < ActiveModel::Validator
def validate(record)
# ...
end
end
module ActiveModel::Validations
module HelperMethods
def validates_my_custom_stuff(*attr_names)
validates_with MyCustomValidator, attr_names
end
end
end
Internally, ActiveModel::Validations
extends HelperMethods, so your validation helper method should be available to all models.
Upvotes: 1