我何时何地需要rails应用程序中的文件?

Lee*_*Lee 27 ruby ruby-on-rails

假设我在rails应用程序的lib目录中有以下文件:

#lib/proxy.rb
module SomeService
  class ServiceProxy
    def do_something
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

如果我想在模型中使用ServiceProxy,我可以像这样使用它:

#app/models/product.rb
require 'proxy'

class Product < ActiveRecord::Base
  def do_something
    proxy = SomeService::ServiceProxy.new
    proxy.do_something
  end
end
Run Code Online (Sandbox Code Playgroud)

这有效,但我注意到如果我想在另一个模型中使用ServiceProxy,我在第二个模型文件中不需要"require'proxy'".似乎在任何模型中都需要"require'proxy'"将其添加到查找路径中.

有人可以在rails应用程序中解释这种行为以及围绕它的最佳实践吗?

谢谢!

更新:根据下面的floyd的答案,如果我的ServiceProxy文件被保存为,

#lib/some_service/service_proxy.rb
Run Code Online (Sandbox Code Playgroud)

然后我不必明确要求该文件.

tfw*_*ght 14

是关于此问题的有用帖子.

简而言之,只有当Rails遵循正确的命名约定时,它才会在lib目录中自动加载类.


Cod*_*lan 6

我通常会将该 require 语句放在配置/初始化文件中,例如 config/initializers/load_proxy.rb