何时调用“要求"在 Rails 中? [英] When to call a "require" in Rails?

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

问题描述

我在 Rails 或 Ruby 中有一个更概念性的问题:

I have a more conceptual question in Rails... or Ruby for that matter:

是否最好在需要它的方法之前调用 require,在类的开头或 Rails 启动时的初始化程序中的某处将我的需求分组?

Is it best to call a require right before the method that needs it, group my requires at the beginning of the class or somewhere in an initializer when Rails boots?

从性能的角度来看,这很重要吗?从可读性的角度?如果我使用 Rails 3 会有什么不同吗?

Does it matter from a performance point of view? From a readability point of view? Does it make a difference if I'm using Rails 3?

谢谢!

推荐答案

如果你关心性能,那么你应该在需要它们的上下文中要求一些东西,这样如果你的代码的那部分没有被执行,库未加载.对 require 的任何后续调用都无效,因为该文件已经加载.这最终看起来像以下内容:

If you're concerned about performance then you should require things in the context of where they are needed so that if that portion of your code is not exercised, the library is not loaded. Any subsequent calls to require have no effect as that file has already been loaded. This ends up looking like something along the lines of:

if (user.using_openid?)
  require 'openid'

  # ... Do OpenID stuff
end

虽然这在资源方面更有效,但可能很难确定应用程序的依赖关系.预先声明这些可以让其他维护软件的人一目了然.请记住,当您忘记应用程序的某些细节时,其他人"总是包括您未来的自己.

While this is more efficient in terms of resources, it can make it very difficult to determine the dependencies of your application. Declaring these up-front makes it clear to other people maintaining the software. Keep in mind that "other people" always includes your future self when you've forgotten about some details of your application.

从技术上讲,您可以在任何时间(晚或早)提出任何要求,但从设计的角度来看,提前声明您的要求会更好.如果您发现有一个元素只是间歇性地使用并且需要异常的时间或内存来加载,那么您可能应该在您的需求文件中预先记录它.例如:

You're technically allowed to require anything at any time, late or early, but declaring your requirements up front is better from a design perspective. If you find that there is an element that is used only intermittently and takes an unusual amount of time or memory to load, then you should probably document that up front in your requirements file. For example:

require 'library1'
require 'library2'
require 'library3'
require 'library4'
require 'library5'

# Other libraries loaded as required:
#  * slowimagelibrary
#  * slowencryptionlibrary
#  * openid

可以说这对 bundler 来说不是问题,因为您可以更正式地预先声明您的 gemsrequire 可以稍后调用.

Arguably this is less of an issue with bundler because you can have your gems declared up front more formally and the actual require call can come later.

这篇关于何时调用“要求"在 Rails 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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