Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gem: include my own module into ActiveModel::Validations

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?

like image 801
Piotr Kruczek Avatar asked Jun 17 '26 22:06

Piotr Kruczek


1 Answers

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.

like image 142
mrgrodo Avatar answered Jun 19 '26 13:06

mrgrodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!