skip to content

In a Rails 8.1 app, what do Rails.autoloaders.main.collapse and Rails.autoloaders.main.ignore change, and when would you use each?

level: seniorimportance: nice to knowfreq 22%

answer

  1. grouping folder versus no-go folder
  2. collapse drops one namespace level
  3. ignore hides files from Zeitwerk
  4. STI hierarchies need preloading
  5. push_dir with a namespace: option

basics

~20 s

collapse keeps a directory managed but stops it from being a namespace, so app/models/filings/motion.rb defines Motion. ignore removes files or directories from Zeitwerk entirely, so they are neither autoloaded nor eager loaded and must be required by hand.

solid answer

~40 s

Called on `Rails.autoloaders.main`, both can go in an initializer. `collapse(dir)` keeps the directory managed but makes it **organisational only**: its files define constants in the parent namespace, so an `app/models/filings` folder grouping an STI hierarchy can hold `Filing`, `Motion` and `Brief` without a `Filings::` prefix. `ignore(path)` makes Zeitwerk skip the files completely: no autoload, no eager load, no reload. Use it for Ruby that does not follow the naming rule or that you `require` yourself, such as middleware; `config.autoload_lib(ignore:)` uses it for `lib`. A collapsed STI folder is often paired with `Rails.autoloaders.main.eager_load_dir` inside `to_prepare` when `eager_load` is off. For the opposite need, an extra namespace, `push_dir(dir, namespace: Services)` gives a root its own namespace.

code

ruby · 6 lines
ruby
# config/initializers/zeitwerk.rb
Rails.autoloaders.main.collapse("#{Rails.root}/app/models/filings")
Rails.autoloaders.main.ignore("#{Rails.root}/app/models/legacy_scripts")

# app/models/filings/motion.rb  => Motion (collapsed)
# app/models/legacy_scripts/*.rb => invisible to Zeitwerk

go deeper

for a junior

Know that a folder normally becomes a namespace and that Rails can be told to treat a folder as grouping only.

for a middle

Explain the difference: collapsed files stay autoloaded and reloadable; ignored files must be required and never reload.

for a senior

Apply them to real layouts: collapse an STI folder and preload it with eager_load_dir, ignore middleware you require, and verify with zeitwerk:check.

for a principal

Keep such exceptions rare and documented, since each one makes the file tree a less reliable map of the constants.

## Two ways to bend the file-to-constant rule Zeitwerk's default is strict: below an autoload path, every directory is a namespace and every `.rb` file defines one constant named after its path. Two loader methods relax it, and they do very different things. | Method | Directory still managed? | Effect on names | Typical use | |---|---|---|---| | `collapse(dir)` | yes: autoloaded, reloaded, eager loaded | the directory adds **no** namespace | folders that only group files | | `ignore(path)` | **no** | not applicable: files are invisible to Zeitwerk | non-conforming Ruby, code you `require` | | `push_dir(dir, namespace: Mod)` | yes, as a new root | the root maps to `Mod` instead of `Object` | `app/services/...` as `Services::...` | | `do_not_eager_load(path)` | yes | unchanged | code that should load only on demand | All of them are methods on a `Zeitwerk::Loader`; in Rails you call them on `Rails.autoloaders.main`. Because Rails sets up the main loader after `config/initializers` run, an initializer is a valid place to configure it. Configuration for the `once` loader must go in `config/application.rb`. ## collapse: a folder that is not a namespace Take a legal-documents app with a single-table-inheritance hierarchy of court filings: `Filing`, `Motion < Filing`, `Brief < Filing`. Grouping them in `app/models/filings/` would, by default, make them `Filings::Motion` and so on, which changes every reference and the `type` column values. Collapsing the folder keeps the grouping and the flat names: ```ruby # config/initializers/preload_stis.rb filings = "#{Rails.root}/app/models/filings" Rails.autoloaders.main.collapse(filings) unless Rails.application.config.eager_load Rails.application.config.to_prepare do Rails.autoloaders.main.eager_load_dir(filings) end end ``` The second half matters for STI. When you query an STI class, Active Record filters on the type names of that class and its loaded `descendants`, but under lazy loading a subclass exists only once something references it. Eager loading that one directory after every reload keeps the hierarchy complete in development and test, where `eager_load` is off. `collapse` also accepts glob patterns, such as `"#{Rails.root}/app/*/filings"`. ## ignore: files Zeitwerk must not touch `ignore` takes files, directories or globs and removes them from the loader: - they are **not autoloaded**, so references fail unless you `require` the file; - they are **not eager loaded**, so `zeitwerk:check` and production boot skip them; - they are **not reloaded**, so edits need a restart. Use it for: 1. Ruby files that do not define the constant their path implies, such as core extensions that reopen `String`, generator templates, or scripts; 2. code that must be loaded once and kept, such as Rack middleware that you `require` in `config/application.rb` before `config.middleware.use`; 3. `lib` folders such as `assets` and `tasks`, which is what `config.autoload_lib(ignore: %w[assets tasks])` does for you. Zeitwerk already skips files that do not end in `.rb` and names that start with a dot, so `ignore` is for Ruby files. ## When neither is the right tool - To **add** a namespace rather than remove one, give a root its own namespace with `Rails.autoloaders.main.push_dir("#{Rails.root}/app/services", namespace: Services)`, after defining `module Services; end`. - To change how one file name is camelized, use the inflector (`inflector.inflect`), not `collapse`. - To keep a directory reloadable but loaded only on demand in production, `do_not_eager_load` is the narrower switch. ## Custom root namespaces in more detail By default `app/services/users/signup.rb` defines `Users::Signup`, because `app/services` is a root that stands for `Object`. Two ways get a `Services::` prefix: 1. **Add a directory level:** `app/services/services/users/signup.rb`. It works with no configuration but reads oddly. 2. **Give the root a namespace:** define the module, then call `push_dir` with `namespace:`: ```ruby # config/initializers/autoloading.rb module Services; end Rails.autoloaders.main.push_dir("#{Rails.root}/app/services", namespace: Services) ``` The namespace must already exist, because `push_dir` expects a class or module object. As with `collapse`, configuration for the `once` loader has to move to `config/application.rb`. Each of these switches makes the tree a little less self-explanatory: a reader can no longer derive every constant from its path without knowing the configuration. Keep the list short and put it in one initializer. ## Checking the result After configuring either method, `bin/rails zeitwerk:check` eager loads the project with the new rules, and `Rails.autoloaders.main.cpath_expected_at("app/models/filings/motion.rb")` should return `"Motion"`.

  • Why does a single-table-inheritance hierarchy misbehave in development without preloading?
    Active Record builds an STI subclass query's type condition from that class and its `descendants`, and a subclass is a descendant only once it has been loaded. With lazy loading, `Motion.all` can run before `EmergencyMotion` was ever referenced, so its rows are missed, and `descendants` is incomplete too. Eager loading that directory in `to_prepare`, or the whole app, fixes it.
  • What must you do for code in an ignored directory to be usable?
    Load it yourself with `require`, because Zeitwerk sets up no autoloads for ignored paths. That also means it is not reloaded and not eager loaded, so edits need a restart and eager-load checks such as `zeitwerk:check` do not cover it.

  • collapse and ignore both just hide a folder from Zeitwerk.
  • An ignored file is still eager loaded in production.
  • Collapsing app/models/filings renames the classes to Filings::Motion.
  • Use collapse to make pdf_exporter.rb define PDFExporter.
  • Zeitwerk loads every STI subclass automatically when the base class loads.