newcomer
newcomer

Reputation: 91

Ruby: What does autoload method do?

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?

Upvotes: 7

Views: 3032

Answers (3)

software_writer
software_writer

Reputation: 4468

Autoloading in Ruby

The Kernel#autoload method speeds up the initialization of your library by lazily loading the modules. It won't load the library or framework code you don't need.

The Ruby version takes two arguments: module (can be either a string or a symbol) and filename (string), and registers the filename to be loaded the first time that module is accessed.

autoload :Payment, "lib/modules/payment.rb"

Autoloading in Rails

Ruby on Rails provides its own autoload method via its Active Support framework by overriding Ruby's autoload method.

It allows you to define autoload based on Rails naming conventions. It automatically guesses the filename based on the module name.

autoload :SecurePassword

If the path is not provided, Rails guesses the path by joining the constant name with the current module name and generating its underscored and lowercase form. Finally, it calls Ruby's autoload method by calling super and passes the module name and the generated path.

For more details, check out: Autoloading Modules in Rails

Upvotes: 1

Peter Brown
Peter Brown

Reputation: 51697

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.

Upvotes: 7

mliebelt
mliebelt

Reputation: 15525

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 :-)

Upvotes: 12

Related Questions