Problem with Rails extension in lib directory subdirectory

I am using Ruby on Rails 3.2.9, and I would like to expand the scope with a custom validator located in the lib/ subdirectory. I have done the following:

 # lib/extension/rails/custom_validator.rb module Extension module Rails class CustomValidator < ActiveModel::EachValidator # ... end end end 

After rebooting the server, I get an Unknown validator: 'CustomValidator' error. How can i solve the problem?


Note I: In config/application.rb I specified config.autoload_paths += %W(#{config.root}/lib) .

Note II: If I put the custom_validator.rb file “directly below” in the lib/ directory (that is, without “submapping” the file), and I use the following code, then it works.

 # lib/custom_validator.rb class CustomValidator < ActiveModel::EachValidator # ... end 
0
source share
1 answer

Try creating a file in the lib folder named "extension.rb" with the following contents

 $:.unshift File.expand_path(File.dirname(__FILE__)) module Extension module Rails autoload :CustomValidator, "extension/rails/custom_validator" end end 

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 method is used.

The previous code assumes that you wrote your validator as follows

 # lib/extension/rails/custom_validator.rb module Extension module Rails class CustomValidator < ActiveModel::EachValidator # ... end end end 

And that you included it in your model as follows

 class MyModel validates_with Extension::Rails::CustomValidator end 

Another option is to define a validator as follows

 # lib/extension/rails/custom_validator.rb class CustomValidator < ActiveModel::EachValidator # ... end 

and then add its directory to the download path of your application

 # config/application.rb config.autoload_paths += %W(#{config.root}/lib/extension/rails) 

And in your model use to check

following:
 class MyModel validates :my_property, :presence => true, :custom => true end 
0
source

All Articles