How to eager load a single directory with Zeitwerk

Zeitwerk is the new autoloader of Rails. It is mandatory starting with Rails 7.0.

Sometimes, a model needs to know all its descendants. They might be organized in a subdirectory:

# Example
app/models/design.rb
app/models/design/light.rb
app/models/design/dark.rb
...

Now imagine that some external code needs to iterate all design subclasses.

To eager load all designs, use this line:

Rails.autoloaders.main.eager_load_dir(Rails.root.join 'app/models/design')

Make sure that app/models/design.rb is not required manually before instructing Rails to autoload it!

Dominik Schöler