我何时何地需要 Rails 应用程序中的文件? [英] When and where do I require files in a rails application?

查看:35
本文介绍了我何时何地需要 Rails 应用程序中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have I have the following file in my lib directory of my rails application:

#lib/proxy.rb
module SomeService
  class ServiceProxy
    def do_something
    end
  end
end

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

If I want to use ServiceProxy in a model, I can use it like so:

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

class Product < ActiveRecord::Base
  def do_something
    proxy = SomeService::ServiceProxy.new
    proxy.do_something
  end
end

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

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.

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

Can someone explain this behavior and the best practice surrounding it in a rails app?

谢谢!

更新:根据下面弗洛伊德的回答,如果我的 ServiceProxy 文件是这样保存的,

UPDATE: Based on floyd's answer below, if my ServiceProxy file was saved as so,

#lib/some_service/service_proxy.rb

那么我就不必明确要求该文件.

then I would not have to explicitly require the file.

推荐答案

这个 是有关此问题的有用帖子.

This is a helpful post about this issue.

简而言之,Rails 会在您的 lib 目录中自动加载类,前提是它们遵循正确的命名约定.

In short, Rails autoloads classes in your lib directory only if they follow the proper naming conventions.

这篇关于我何时何地需要 Rails 应用程序中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆