【问题标题】:How to list all autoload paths in Rails如何列出 Rails 中的所有自动加载路径
【发布时间】:2012-11-29 15:27:59
【问题描述】:

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

当我这样做时,在 Rails 控制台中,它只列出添加到配置中的自定义路径:

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

【问题讨论】:

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


    【解决方案1】:

    您可以通过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

    【讨论】:

    • 也适用于 Rails 5
    • 也可以在 Rails 6 中工作!
    【解决方案2】:

    更新:请在下面使用 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 添加的所有自动加载路径和自定义加载路径。

    【讨论】:

      【解决方案3】:
      Rails.application.instance_variable_get(:"@_all_autoload_paths")
      

      【讨论】:

        猜你喜欢
        • 2015-09-12
        • 2011-10-18
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 2013-12-26
        • 2022-01-11
        相关资源
        最近更新 更多