The autoload Method in Ruby
Ruby has an in-built module autoload, which comes into action whenever a specific module or a class is accessed or called upon from the parent or calling class or module. Upon receiving a call, this module registers the corresponding file path to the called module. This is performed when the first call to the specified module is made. This is an instance of a lazy loading mechanism where this module is loaded only upon explicitly invoking and calling the module.
Syntax:
autoload(mod-ch,'file-name.rb')
Here, mod-ch is the module/class to be called and file-name.rb is the file path to be called.
The following examples illustrate the use of the autoload method:
Example 1:
File name: f1.rb
Ruby
module A
autoload(: B , './f2.rb' )
puts "Module B has not been loaded"
B
puts "Module B has been loaded"
end
|
File name: f2.rb
Ruby
module B
puts 'Module B has started loading'
end
|
Upon execution of file f1.rb, the following code produces this output:
Module B has not been loaded
Module B has started loading
Module B has been loaded
Example 2:
File name: p.rb
Ruby
module P
autoload(: C , './c.rb' )
p autoload?(: C )
C
p autoload?(: C )
end
|
File name: c.rb
Ruby
module C
puts 'In progress'
end
|
Upon execution of file p.rb, the following code produces this output:
'./c.rb'
In progress
nil
Explanation: In the above example, when the explicit call to the module is not made, the autoload method returns the file path of the file containing the module. Upon calling the module, the contents of the module are printed, which is a string “In progress in this case”. After the module is loaded, the second call to the autoload function, returns the value nil because the module C is already loaded.
Working of the autoload Module:
Internally, the autoload method associates a constant value with a filename that is loaded. The constant is then referenced by the filename of which the path is specified. The call to this method flags the created constant had an undefined value.
File name: p.rb
Ruby
module A
autoload(: C , './c.rb' )
p constants
end
|
File name: c.rb
Upon execution of file p.rb, the following code produces this output:
[:C]
Here, the constant is automatically created even when an explicit call to the module is not made. The constant is created with the same name as the module.
Usage of the autoload method
- The autoload module ensures if the specified module or class has been loaded and exists in the namespace.
- Depending on the execution of the program flow, the module is invoked.
- It also verified if the child or called module is registered in the program execution flow.
Last Updated :
01 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...