Ruby-on-rails 我何时何地需要 Rails 应用程序中的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2120824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When and where do I require files in a rails application?
提问by Lee
Let's say I have I have the following file in my lib directory of my rails application:
假设我的 rails 应用程序的 lib 目录中有以下文件:
#lib/proxy.rb
module SomeService
class ServiceProxy
def do_something
end
end
end
If I want to use ServiceProxy in a model, I can use it like so:
如果我想在模型中使用 ServiceProxy,我可以像这样使用它:
#app/models/product.rb
require 'proxy'
class Product < ActiveRecord::Base
def do_something
proxy = SomeService::ServiceProxy.new
proxy.do_something
end
end
This works, but I noticed if I want to use ServiceProxy in another model, I do not need "require 'proxy'" in the second model file. It seems having "require 'proxy'" once in any model will add it to the lookup path.
这有效,但我注意到如果我想在另一个模型中使用 ServiceProxy,我不需要在第二个模型文件中“需要‘代理’”。似乎在任何模型中“需要‘代理’”一次都会将其添加到查找路径中。
Can someone explain this behavior and the best practice surrounding it in a rails app?
有人可以在 Rails 应用程序中解释这种行为以及围绕它的最佳实践吗?
Thanks!
谢谢!
UPDATE: Based on floyd's answer below, if my ServiceProxy file was saved as so,
更新:根据下面弗洛伊德的回答,如果我的 ServiceProxy 文件是这样保存的,
#lib/some_service/service_proxy.rb
then I would not have to explicitly require the file.
那么我就不必明确要求该文件。
采纳答案by tfwright
回答by Cody Caughlan
I would generally place that require statement in a config/initalizer file, e.g. config/initializers/load_proxy.rb
我通常会将该 require 语句放在配置/初始化文件中,例如 config/initializers/load_proxy.rb
回答by Emily
Have you tried removing it from the first model as well? I believe Rails will automatically load any files you have in your libdirectory without you ever having to requirethem explicitly.
您是否也尝试将其从第一个模型中删除?我相信 Rails 会自动加载您lib目录中的任何文件,而无需您require明确地加载它们。
回答by Tim Snowhite
Also note that some environment.rb's come with these comments:
另请注意,某些 environment.rb 带有以下注释:
Rails::Initializer.run do |config|
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
config.load_paths << "#{RAILS_ROOT}/app/models/some_model_group"
config.load_paths << "#{RAILS_ROOT}/lib"
end
回答by hiveer
Rails will auto add /lib /vendor /appthis dir into autoload path. When you need some constants in it, you need to require the specific file. And you don't need to require it the second time, because it would be useless.
Rails 会自动/lib /vendor /app将此目录添加到自动加载路径中。当您需要其中的一些常量时,您需要要求特定文件。你不需要第二次要求它,因为它没有用。

