In this article we’re going to explore the following topics:
autoloadregistration & lazy loading
Module#autoloadmethod behind the scene
Feel free to have a look to the
Requiring a file in Rubyarticle if you are not familiar with the
autoload registration & lazy loading
Module#autoload method registers a file path to be loaded the first time that a specified module or class is accessed in the namespace of the calling module or class.
Let’s detail a simple example to break down the previous assertion.
now let’s run our Ruby script
$> ruby car.rb
The Engine module isn’t yet loaded!
The Engine module is loading!
The Engine module has been successfully loaded!
Here we see that after a call to
autoload(:Engine, ‘./engine.rb’) The
engine.rb is not yet loaded.
In effect, this file is only loaded when we explicitly call the
This mechanism allows Ruby to only load the files that contain the modules/classes used by the execution flow of the running program.
Module#autoload? is in charge of checking if a registered module/class in a specific namespace has already been loaded or not.
It’s also used for checking if a module is registered (or not) as autoload in a specific namespace
The module B is loading!
The first call to
autoload? :B returns the
"./b.rb" file path.
B module is loaded via a loading of the
Finally, the second call to
autoload? :B returns
nil because the
B module is already loaded.
C module outside of the the
The call to
autoload? :C within the
A namespace returns
nil because the
:C module is registered as
autoload in the top-level namespace and not in the
In contrary, the second call to
autoload? :C is invoked within the top-level namespace. As it’s within the same namespace as the
autoload(:C, './c.rb') registration then it returns the
"./c.rb" file path.
Now that we are more familiar with the
autoload registration mechanism, let’s dive into what happens behind the scene when we register and call a module.
Module#autoload method behind the scene
Module#autoload method is called within a specific namespace then the module/class and the file path given as arguments of the method are stored in an internal hash table.
Let’s have a look to this example
Here, we can see that the
B constant exists even if it hasn’t been loaded yet.
In effect, a call to
autoload will automatically create a constant named as the first argument of the method and flagged as
autoload registered. The value of this constant will be undefined and NOT
B module will be invoked then Ruby will search for the
B entry within the constants hash table of the
It’ll then load the file using the
Finally the constant hash table will unflag as
ONE MORE THING ⬇
Feel free to subscribe here: www.rubycademy.com
Thank you for taking the time to read this post :-)
Feel free to 👏 and share this article if it has been useful for you. 🚀
Also, as I post an article every 3 days, feel free to follow me to be notified of my new releases.
Here is a link to my last article:
OpenStruct in Ruby.