何时在Ruby中使用`require`,`load`或`autoload`? [英] When to use `require`, `load` or `autoload` in Ruby?
问题描述
我了解Ruby中require
,load
和autoload
之间的细微差别,但是我的问题是,您如何知道要使用哪个?
除了能够在匿名模块中包装" load
之外,require
似乎是首选.
但是autoload
然后允许您延迟加载文件-听起来不错,但我不确定您实际上从require
一种方法优先于另一种方法吗?是否存在一种方法脱颖而出的情况?
通常,您应该使用require
. load
每次都会重新加载代码,因此,如果您从多个模块中执行代码,则将需要做很多额外的工作. autoload
的懒惰在理论上听起来不错,但是许多Ruby模块执行的功能类似于对其他类进行猴子修补,这意味着程序无关部分的行为可能取决于是否使用了给定的类. /p>
如果您想创建自己的自动重新加载程序,以便每次更改代码或每次有人访问URL时都加载代码(出于开发目的,因此您不必每次都重新启动服务器),请使用load
因为那是合理的.
I understand the subtle differences between require
, load
and autoload
in Ruby, but my question is, how do you know which one to use?
Other than being able to "wrap" a load
in an anonymous module, require
seems to be preferred.
But then autoload
allows you to lazy load files -- which sounds fantastic but I'm not sure practically what you gain over require
Is one method preferred over the other? Is there a situation where one method stands out?
Generally, you should use require
. load
will re-load the code every time, so if you do it from several modules, you will be doing a lot of extra work. The lazyness of autoload
sounds nice in theory, but many Ruby modules do things like monkey-patching other classes, which means that the behavior of unrelated parts of your program may depend on whether a given class has been used yet or not.
If you want to make your own automatic reloader that loads your code every time it changes or every time someone hits a URL (for development purposes so you don't have to restart your server every time), then using load
for that is reasonable.
这篇关于何时在Ruby中使用`require`,`load`或`autoload`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!