This article explains class & module autoloading in Ruby. Including the new “Zeitwerk” gem which is part of Rails 6.
Let’s start with a question…
How do we bring together multiple source code files into one?
Requiring a file makes Ruby read it & run the code inside. But if we have a list of required files we probably don’t need to load ALL of them.
At least not right away…
How can we load files only when we need them so we can start our application faster?
That’s where autoloading comes in!
How to Use Autoloading
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
Autoloading in Rails BEFORE Rails 6
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:
- Put your file where it can be found (as defined by
- Define one class / module per file
- Name the file after the class name, using underscores (
Whenever your code references any of these class names, Rails will know where to find them.
Autoloading in Rails AFTER Rails 6
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.
- If you have
"lib"in autoload, and you want to define
"Fruit::Orange", then the file name has to be
- But if you have
"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! 🙂