Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

module - When to use `require`, `load` or `autoload` in Ruby?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...