什么时候在 Ruby 中使用 `require`、`load` 或 `autoload`? [英] When to use `require`, `load` or `autoload` in Ruby?

查看:36
本文介绍了什么时候在 Ruby 中使用 `require`、`load` 或 `autoload`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 Ruby 中 requireloadautoload 之间的细微差别,但我的问题是,你怎么知道应该选择哪个利用?

I understand the subtle differences between require, load and autoload in Ruby, but my question is, how do you know which one to use?

除了能够在匿名模块中包装"loadrequire 似乎更受欢迎.

Other than being able to "wrap" a load in an anonymous module, require seems to be preferred.

但是 autoload 允许你延迟加载文件——这听起来很棒,但我不确定你实际上从 require

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?

推荐答案

通常,您应该使用 require.load 每次都会重新加载代码,因此如果您从多个模块执行此操作,您将做很多额外的工作.autoload 的惰性在理论上听起来不错,但是许多 Ruby 模块会做类似猴子修补其他类的事情,这意味着程序中不相关部分的行为可能取决于是否使用了给定的类不管有没有.

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.

如果您想制作自己的自动重新加载器,在每次更改或每次有人点击 URL 时加载您的代码(出于开发目的,因此您不必每次都重新启动服务器),然后使用 加载是合理的.

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屋!

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