Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: What does autoload method do?

Tags:

ruby

module ActionController extend ActiveSupport::Autoload

  autoload :Base
  autoload :Caching
  autoload :Metal
  autoload :Middleware
end

Can anyone elaborate with example/sample output what autoload method does?

like image 371
newcomer Avatar asked Jul 25 '11 11:07

newcomer


2 Answers

Autoload ensures that the class or module is automatically loaded if needed. There is a nice article of Peter Cooper named "Ruby Techniques Revealed: Autoload" that explains the differences to require. I don't want to repeat his example here :-)

like image 110
mliebelt Avatar answered Oct 31 '22 23:10

mliebelt


autoload is an alternative to require when the code to be executed is within a module. The main functional difference is when the code is actually executed. autoload is frequently used in ruby gems to speed up application load time.

With autoload, the first time you use the module constant, it is loaded from the specified file. With require, it is executed as soon as you require it. Note that the Ruby implementation of autoload requires both a module and filename, but the Rails version in your example makes the filename optional.

As far as an example goes, there really isn't much more than what you have in your question. These modules would be executed when you use ActionController::Base, ActionController::Caching, etc.

like image 43
Peter Brown Avatar answered Oct 31 '22 23:10

Peter Brown