2012-02-24 36 views
3

我正在嘗試使用myapplication/somefolder下的文件。谷歌和#1說我應該補充一點:如何在Rails應用程序的根目錄下自動加載文件夾中的文件

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

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

但是文件不會被加載。

我試過namig somefolder/myclass.rbclass Myclassclass Somefolder::Myclass但仍然沒有運氣。

我可以看到,DIR是在控制檯Rails.application.config.autoload_paths發現確實包括我/path/to/myapplication/somefolder目錄,這樣應該沒問題。

圍繞此主題的所有其他問題使用theapp/app/somefoldertheapp/lib/somefolder但不theapp/somefolder所以也許這就是它爛的地方。

所以我嘗試引用與::Somefolder::MyClass類,但沒有幫助。

我用Rails 3.2.1

+0

更多的研究表明,'的ActiveSupport :: Dependencies.autoload_paths'不包含我的'在運行時somefolder'路徑。任何想法爲什麼? – hakunin 2012-02-24 11:56:04

回答

2

今天剛剛遇到這個,我決定深入潛水。

您在ActiveSupport::Dependencies.autoload_paths中看不到的原因是您要添加到config.autoload_paths的路徑config/application.rb的原因是它們不會在應用程序初始化之前被複制。見rails/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 
1

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

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

但我現在還在找工作,爲什麼config.autoload_paths沒有工作,所以,如果你發佈一個aswer到的原因,我會接受它!

+0

我也有同樣的問題:(我使用的是Rails 3.2.3。 – Zeck 2012-05-15 12:27:15

1

您應該命名爲somefolder/my_class.rb以便自動加載MyClass。您還應該在config/application.rb中保留config.autoload_paths += %W(#{config.root}/somefolder)行。

相關問題