问题
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
回答1:
Try to have a file in the lib folder named "extension.rb" with the following content
$:.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 technique is used.
The previous code assumes that you've written your validator like following
# lib/extension/rails/custom_validator.rb
module Extension
module Rails
class CustomValidator < ActiveModel::EachValidator
# ...
end
end
end
And that you've included it in your model like the following
class MyModel
validates_with Extension::Rails::CustomValidator
end
Another option would be to define the validator as follows
# lib/extension/rails/custom_validator.rb
class CustomValidator < ActiveModel::EachValidator
# ...
end
and then add its directory to the load path of your application
# config/application.rb
config.autoload_paths += %W(#{config.root}/lib/extension/rails)
And in your model use the following to validate
class MyModel
validates :my_property, :presence => true, :custom => true
end
来源:https://stackoverflow.com/questions/13893659/trouble-on-extending-rails-in-a-sub-directory-of-the-lib-directory