I am using Ruby on Rails 3.2.9 and I would like to extend the framework with a custom validator located in a sub-directory of the lib/
directory. I implemented the following:
# lib/extension/rails/custom_validator.rb
module Extension
module Rails
class CustomValidator < ActiveModel::EachValidator
# ...
end
end
end
After I restart the server I get the Unknown validator: 'CustomValidator'
error. How can I solve the problem?
Note I: In the config/application.rb
file I stated config.autoload_paths += %W(#{config.root}/lib)
.
Note II: If I put the custom_validator.rb
file "directly under" the lib/
directory (that is, without "sub-directoring" the file) and I use the following code then it works.
# lib/custom_validator.rb
class CustomValidator < ActiveModel::EachValidator
# ...
end
Try to have a file in the lib folder named "extension.rb" with the following content
checkout http://www.rubyinside.com/ruby-techniques-revealed-autoload-1652.html and https://github.com/macournoyer/thin/blob/c8f4627bf046680abb85665f28ab926e36c931db/lib/thin.rb for how this technique is used.
The previous code assumes that you've written your validator like following
And that you've included it in your model like the following
Another option would be to define the validator as follows
and then add its directory to the load path of your application
And in your model use the following to validate