This article explains class & module autoloading in Ruby.
Let’s start with a question…
How do we bring together multiple source code files into one?
This tells Ruby to look for a file & run the code inside it.
But sometimes we don’t need to load these files.
At least not right away…
So how can we load files only when we need them?
That’s where autoloading comes in!
Ruby has a built-in autoloading feature.
It’s based on constants.
When a constant like
Coconut is found for the first time, Ruby will try to load its associated file.
You need to register this constant with its file name.
autoload :Coconut, "lib/coconut.rb"
Now Ruby knows where to look whenever you want to use the
Coconut class or module.
But you know what would be even better?
Imagine if you didn’t have to register constants manually & Ruby knew exactly where to find everything.
This is what Rails does, but before Rails 6 it didn’t use this
I don’t fully understand how it works, but Rails uses
const_missing, instead of
autoload to automatically find & load files into your project.
Why is that useful?
Because it means you don’t have to use
require in your Rails projects.
Convention over configuration…
It all happens automatically, given that you follow the rules.
The rules are:
Whenever your code references any of these class names, Rails will know where to find them.
Rails 6 introduces a new constant autoloading mechanism.
It’s called Zeitwerk.
How is this different from “classic” Rails autoloading?
const_missing approach used by older Rails versions, which lacks information – like module nesting – resulting in a number of limitations.
Zeitwerk uses Ruby’s
This new implementation follows similar file-naming conventions.
Zeitwerk uses the file name to infer the class name,
Which is exactly the opposite of before.
Btw, you can still use
autoload_paths, but you only want to add BASE paths, like
"/lib", instead of
It’s the way this works with namespaces & nesting.
"lib"in autoload, and you want to define
"Fruit::Orange", then the file name has to be
"lib/fruit"in autoload, then you would have to use another folder, so your file name becomes
"lib/fruit/fruit/orange.rb"for the same class.
The best part?
This new functionality isn’t glued to Rails, so you can use it in your non-Rails projects!
You have learned about module autoloading in Ruby, exactly what it is & how it works!
With this new understanding, you’ll be able to structure your Ruby projects in the most effective way.
It’s your turn, open up your editor & have some fun.
Thanks for reading! 🙂