【问题标题】:What is the best way to load files from the lib folder that add methods to ~existing~ classes in Rails 3?从 lib 文件夹加载文件的最佳方法是向 Rails 3 中的 ~existing~ 类添加方法?
【发布时间】:2011-04-30 13:32:32
【问题描述】:

我正在使用config.autoload_paths 以与related question 非常相似的方式从 Rails 3 项目的 lib 目录加载类。

具体来说,我已将这些行添加到 config/application.rb 文件中:

config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

但是,这种方法不适用于我的现有类。当我添加像 lib/extensions/string.rb 这样的文件时:

class String
  def foo
    puts "foo"
  end
end

我收到undefined method 'foo' for "":Stringerror。通过各种搜索,我感觉这个问题与这些文件的延迟加载有关。我尝试使用config.eager_load_paths,但无法让它工作。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    我正在完全按照你在我的应用程序中描述的那样做,唯一的区别是我有一个名为extensions.rb的初始化程序strong> 使用以下代码:

    Dir.glob('lib/extensions/*').each { |f| require f }
    

    【讨论】:

    • 这个初始化方法对我有用。但是,我不得不将其稍微更改为:Dir.glob("#{Rails.root}/lib/extensions/*").each { |f| require f } 你同意吗?
    • 另外,在blog post的另一个问题中引用了一个很好的自动加载与需要的例子
    • 使用完整路径可能更好,但我的应用程序不需要。不知道为什么会这样。
    • 你应该使用 eager_load_paths 来保证线程安全并在更改时自动重新加载类,正如在此处发布的 blog.plataformatec.com.br/2012/08/…
    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多