比方說,我有我在我的lib我的Rails應用程序目錄中的下列文件:何時何地需要軌道應用程序中的文件?
#lib/proxy.rb
module SomeService
class ServiceProxy
def do_something
end
end
end
如果我想在一個模型中使用ServiceProxy,我可以用它像這樣:
#app/models/product.rb
require 'proxy'
class Product < ActiveRecord::Base
def do_something
proxy = SomeService::ServiceProxy.new
proxy.do_something
end
end
這有效,但我注意到如果我想在另一個模型中使用ServiceProxy,我不需要在第二個模型文件中需要「代理」。在任何模型中,似乎都會有「需要」代理「」將其添加到查找路徑中。
有人可以解釋這種行爲和圍繞它在軌應用程序的最佳做法嗎?
謝謝!
UPDATE: 基於以下弗洛伊德的回答,如果我的ServiceProxy文件保存爲如此,
#lib/some_service/service_proxy.rb
那麼我不會有明確要求的文件。
非常有幫助。我只是一直使用命名約定,所以不知道如果我不這樣做不會工作。 – Emily 2010-01-22 22:06:28
我不知道Rails中是否發生了一些變化,但是我總是需要在config/application.rb中添加以上行爲:config.autoload_paths + =%W(#{config.root}/lib) – 2013-07-10 15:06:41
這篇文章更詳細:http://urbanautomaton.com/blog/2013/08/27/rails-autoloading-hell/ – 2014-10-09 13:25:01