3

我正在尝试将文件放在myapplication/somefolder. 谷歌和 Stackoverflow 说我应该添加这个:

config.autoload_paths += %W(#{config.root}/somefolder)

在我的config/application.rb,所以我做到了。

但是文件没有被加载。

somefolder/myclass.rb我都尝试了 namig class Myclassclass Somefolder::Myclass但仍然没有运气。

我可以看到Rails.application.config.autoload_paths在控制台中找到的目录确实包含我的/path/to/myapplication/somefolder目录,所以应该没问题。

围绕这个主题的所有其他问题都使用theapp/app/somefolderortheapp/lib/somefolder但不是theapp/somefolder所以也许这就是它变得腐烂的地方。

所以我尝试引用这个类,::Somefolder::MyClass但没有帮助。

我正在使用 Rails 3.2.1

4

3 回答 3

2

今天我自己遇到了这个问题,并决定深入研究。

您在添加的ActiveSupport::Dependencies.autoload_paths路径中看不到的原因是在应用程序初始化之前它们不会被复制。见宝石:config.autoload_pathsconfig/application.rbrails/engine.rbrailties

module Rails
  class Engine < Railtie
    …

    # Set the paths from which Rails will automatically load source files,
    # and the load_once paths.
    #
    # This needs to be an initializer, since it needs to run once
    # per engine and get the engine as a block parameter
    initializer :set_autoload_paths, :before => :bootstrap_hook do |app|
      ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths)
      ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths)

      # Freeze so future modifications will fail rather than do nothing mysteriously
      config.autoload_paths.freeze
      config.eager_load_paths.freeze
      config.autoload_once_paths.freeze
    end

    …

    def _all_autoload_paths
      @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
    end

    …
  end
end

您是否有任何机会尝试从需要的脚本或模块中调用MyClassconfig/application.rb或者甚至更早地从需要调用的脚本或模块中调用config/application.rb?如果是这样,您必须明确要求文件定义MyClass,例如:

require File.expand_path('../../somefolder/my_class',  __FILE__)
# now use MyClass
于 2013-08-28T23:53:03.687 回答
1

解决方法是直接去ActiveSupport::Dependencies.autoload_paths

ActiveSupport::Dependencies.autoload_paths << "#{config.root}/somefolder"

但我仍在寻找 config.autoload_paths 不起作用的原因,所以如果您对此发表声明,我会接受!

于 2012-02-24T13:19:22.830 回答
1

您应该命名somefolder/my_class.rb以便自动加载MyClass. 您还应该将该config.autoload_paths += %W(#{config.root}/somefolder)行保留在您的config/application.rb.

于 2012-09-14T14:02:49.133 回答