How to eager load a single directory with Zeitwerk

Posted . Visible to the public.

Zeitwerk is the new autoloader of Rails. It is mandatory from 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 the Design class needs to iterate all designs.

To eager load all designs, use this line:

Rails.autoloaders.main.eager_load_dir("#{Rails.root}/app/models/design")

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

Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2024-11-20 12:06)