How to initialize custom ActiveModel Validators in Rails 3+ app from within a Rails Engine

I'm trying to load some custom Validators from a Rails Engine but my application keeps failing due to the validator not being recognized.

What is the proper way & time to initialize the validators in the engine?

For example I have:

    class NullityValidator < ActiveModel::EachValidator
      # Validates whether <tt>value</tt> is <tt>nil?</tt>.
      def validate_each(record, attribute, value)
        record.errors.add(attribute, :not_nil) unless value.nil?
      end
    end

From within my engines class Engine < Rails::Engine I have tried a few different ways to initialize the custom validators such as:

config.before_initialize do
  class NullityValidator < ActiveModel::EachValidator
  end
end

config.after_initialize do
  class NullityValidator < ActiveModel::EachValidator
  end
end

initializer 'ab_gem.validators' do |app|
  ActiveSupport.on_load :active_model do
    class NullityValidator < ActiveModel::EachValidator
    end
  end
end

initializer 'ab_gem.validators' do |app|
  ActiveSupport.on_load :active_record do
    class NullityValidator < ActiveModel::EachValidator
    end
  end
end

initializer 'ab_gem.validators' do |app|
  class NullityValidator < ActiveModel::EachValidator
  end
end

I also tried moving these into a custom module to load, but none of these methods are initializing / loading properly.

Anytime my applications model is being loaded I receive Unknown validator: 'NullityValidator'

Answers


The solution was incredibly more simple and elegant than I thought... Just create a config/initializers/ folder for your initializers, and drop the validators there to be loaded in the proper order.

So just made:

config/initializers/validators.rb

Drop in your validator:

class NullityValidator < ActiveModel::EachValidator
  # Validates whether <tt>value</tt> is <tt>nil?</tt>.
  def validate_each(record, attribute, value)
    record.errors.add(attribute, :not_nil) unless value.nil?
  end
end

Then your good to go. I was under the impression defining an initializer within your engine.rb railtie would accomplish the same thing, but apparently not. This is much cleaner and better practice in my opinion anyway though.


Need Your Help

SQL Server - how to determine if indexes aren't being used?

sql-server database performance indexing

I have a high-demand transactional database that I think is over-indexed. Originally, it didn't have any indexes at all, so adding some for common processes made a huge difference. However, over ti...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.