在"lib"目录的子目录中扩展Rails时遇到问题 [英] Trouble on extending Rails in a sub-directory of the 'lib' directory

查看:100
本文介绍了在"lib"目录的子目录中扩展Rails时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ruby on Rails 3.2.9,并且我想使用自定义验证器位于lib/目录的子目录中.我实现了以下内容:

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

重新启动服务器后,出现Unknown validator: 'CustomValidator'错误.我该如何解决这个问题?

After I restart the server I get the Unknown validator: 'CustomValidator' error. How can I solve the problem?

注意I :在config/application.rb文件中,我说了config.autoload_paths += %W(#{config.root}/lib).

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

注释II :如果将custom_validator.rb文件直接放置在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

推荐答案

尝试在lib文件夹中创建一个名为"extension.rb"的文件,其内容如下:

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

结帐 http://www.rubyinside.com/ruby-techniques -revealed-autoload-1652.html https://github.com/macournoyer/thin/blob/c8f4627bf046680abb85665f28ab926e36c931db/lib/thin.rb 了解如何使用此技术.

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

这篇关于在"lib"目录的子目录中扩展Rails时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆