如何在Rails 3中列出所有自动加载路径

时间:2012-11-29 15:27:59

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

如何列出Rails 3中的所有自动加载路径?

在我执行此操作时,在Rails控制台中,它仅列出添加到配置的自定义路径:

$ rails c
Loading development environment (Rails 3.2.9)
1.9.3p194 :001 > MyRailsApp::Application.config.autoload_paths
=> [] 

3 个答案:

答案 0 :(得分:18)

您可以通过ActiveSupport::Dependencies.autoload_paths

访问所有自动加载路径

从控制台调用它或从命令行运行rails r 'puts ActiveSupport::Dependencies.autoload_paths'

此处有更多信息(对于Rails 4,但它也适用于Rails 3): http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoload-paths

答案 1 :(得分:16)

更新:请使用下面的ActiveSupport :: Dependencies.autoload_paths查看Laura的答案。我在这里留下了这个答案作为替代方法。

在Rails应用程序模块中包含的Rails::Engine中,有以下方法:

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

所以,你可以这样做:

(MyRailsApp::Application.config.autoload_paths + MyRailsApp::Application.config.eager_load_paths + MyRailsApp::Application.config.autoload_once_paths).uniq

或:

[:autoload_paths, :eager_load_paths, :autoload_once_paths].collect{|m|MyRailsApp::Application.config.send(m)}.flatten.uniq

或只是:

MyRailsApp::Application._all_autoload_paths

Rails 3.2.9中的默认结果是:

["/path/to/my_rails_app/app/assets", "/path/to/my_rails_app/app/controllers", "/path/to/my_rails_app/app/helpers", "/path/to/my_rails_app/app/mailers", "/path/to/my_rails_app/app/models"]

这应包括由其他gem和自定义加载路径添加的所有自动加载路径。

答案 2 :(得分:1)

Rails.application.instance_variable_get(:"@_all_autoload_paths")