Trouble on extending Rails in a sub-directory of the 'lib' directory

让人想犯罪 __ 提交于 2019-12-13 03:58:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!