When to use `require`, `load` or `autoload` in Ruby?
RubyModuleRuby Problem Overview
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?
Ruby Solutions
Solution 1 - 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.
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.
Solution 2 - Ruby
mylibrary.rb
puts "I was loaded!"
class MyLibrary
end
Try in irb
irb(main):001:0> require 'mylibrary'
I was loaded!
=> true
irb(main):001:0> autoload :MyLibrary, 'mylibrary'
=> nil
irb(main):002:0> MyLibrary.new
I was loaded!
=> #<MyLibrary:0x0b1jef>
See the difference.
Solution 3 - Ruby
here's what you gain with autoload
over require
:
autoload
is primarily for speeding up the initialization phase of your Ruby program or Rails application. By not loading the resources until they are needed, it can speed up things quite a bit.
Another advantage is that you may not need to load some parts of the code, if the user doesn't use certain features -- thereby improving load time and reducing the memory footprint.
Solution 4 - Ruby
Apart from what others have already told you, future of autoload
is uncertain. It was scheduled to be deprecated in Ruby 2.0, but the deprecation wasn't made in time for the 2.0 feature freeze. It is now expected that autoload
will be deprecated in Ruby 2.1, but that is not even certain anymore.