开发者

Ruby: What does autoload method do?

module ActionController extend ActiveSupport::Autoload

  autoload :Base
  autoload :Caching
  autol开发者_开发技巧oad :Metal
  autoload :Middleware
end

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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜