In a Rails 8.1 app, how does Zeitwerk decide which constant app/services/filings/deadline_calculator.rb must define, and how do you check the whole tree?
answer
- file names decide constant names
- camelize each path segment
- app subfolders are root directories
- concerns folders are roots too
- bin/rails zeitwerk:check eager loads
basics
~10 sZeitwerk camelizes each path segment below an autoload path, so app/services/filings/deadline_calculator.rb must define Filings::DeadlineCalculator. bin/rails zeitwerk:check eager loads the app and names any file that defines the wrong constant.
solid answer
~40 sEvery subdirectory of `app` that exists at boot, except `assets`, `javascript` and `views`, is an **autoload path**: a root directory that stands for the top-level namespace. Below a root, Zeitwerk turns each directory into a namespace and each file name into a constant using Rails' inflector, which falls back to `String#camelize`. So `app/services/filings/deadline_calculator.rb` must define `Filings::DeadlineCalculator`; `services` adds no namespace. Rails sets up the autoloads, so application code needs no `require`. If a file defines something else, a reference to the expected name fails and an eager load raises `Zeitwerk::NameError` ("expected file ... to define constant ..., but didn't"). `bin/rails zeitwerk:check` eager loads the project and prints "All is good!" or the first offending file. A new app's `config/environments/test.rb` sets `config.eager_load = ENV["CI"].present?`, so CI catches the same errors.
code
ruby · 15 lines# app/services/filings/deadline_calculator.rb
module Filings
class DeadlineCalculator
def initialize(filing)
@filing = filing
end
def due_on
@filing.served_on + 21
end
end
end
# Anywhere in the app, with no require:
# Filings::DeadlineCalculator.new(filing).due_ongo deeper
Recall the rule: one file, one constant, named after its path below the app subfolder. Know that classes under the autoload paths need no require.
Explain autoload paths as root directories, the camelize step, nested roots such as concerns, and why a bad name fails only on eager load.
Show how you keep naming errors out of production: zeitwerk:check, eager loading in CI, and reading a Zeitwerk::NameError back to the file and the expected constant.
Treat the directory layout as a contract the whole team signs: decide where new kinds of objects live and enforce it with eager loading in CI.
## Autoload paths: where Zeitwerk looks Rails 8.1 uses **Zeitwerk** as its only autoloader; the old `classic` mode was removed in Rails 7.0. Rails creates two Zeitwerk loaders, `Rails.autoloaders.main` and `Rails.autoloaders.once`, and hands them a list of directories called **autoload paths** (Zeitwerk's docs call them *root directories*). Each root stands for the top-level namespace, `Object`. By default the autoload paths include: - every subdirectory of `app` that exists when the application boots, **except** `app/assets`, `app/javascript` and `app/views`; - every `app/*/concerns` directory, such as `app/models/concerns` and `app/controllers/concerns`; - `lib`, because a new app's `config/application.rb` calls `config.autoload_lib(ignore: %w[assets tasks])`; - the autoload paths of any engines the app depends on. A folder you add, such as `app/services` or `app/forms`, becomes an autoload path with no configuration, provided it exists at boot. ## The file-to-constant rule Inside a root, **the file system decides the constant names**. Zeitwerk walks the tree and maps each directory to a namespace and each `.rb` file to a constant. To turn a basename into a constant name it asks the inflector; Rails' inflector checks its own override table and otherwise calls `String#camelize`. | File | Constant it must define | |---|---| | `app/models/filing.rb` | `Filing` | | `app/services/filings/deadline_calculator.rb` | `Filings::DeadlineCalculator` | | `app/controllers/admin/dockets_controller.rb` | `Admin::DocketsController` | | `app/models/concerns/stampable.rb` | `Stampable` (not `Concerns::Stampable`) | | `lib/docket/pdf_exporter.rb` | `Docket::PdfExporter` | Two consequences matter in interviews: 1. **The root itself adds no namespace.** `app/services` is a root, so its files start at the top level. Wanting `Services::...` takes a subdirectory or a custom root namespace. 2. **Nested roots are independent.** `app/models/concerns` is a root of its own, so its files define top-level constants rather than `Concerns::...`. A directory with no matching `.rb` file still works as a namespace: Zeitwerk creates a plain module for `Filings` the first time it is used (an **implicit namespace**). ## What happens when a file breaks the rule Zeitwerk does not scan files to find out what they define. It sets up an autoload for the *expected* constant and loads the file when that constant is first referenced. If the file then defines something else: - **Lazy loading (development):** a caller that uses the expected name loads the file and gets the same `Zeitwerk::NameError`; a caller that uses the name the file really defines gets an ordinary `NameError: uninitialized constant`, because nothing autoloads that name. If nothing touches the file, nothing fails. - **Eager loading (production, CI, `zeitwerk:check`):** Zeitwerk loads every file at boot and raises `Zeitwerk::NameError`, a subclass of `NameError`, with "expected file .../deadline_calculator.rb to define constant Filings::DeadlineCalculator, but didn't". That asymmetry is why a naming slip can pass every manual check in development and then stop a production deploy at boot. ## Checking the tree Rails gives you three ways to surface the problem before production does: 1. `bin/rails zeitwerk:check` prints "Hold on, I am eager loading the application.", eager loads everything, and ends with "All is good!" or aborts with the offending file. It also warns about autoload paths that are **not** eager loaded, because it cannot check those. 2. A new app's `config/environments/test.rb` sets `config.eager_load = ENV["CI"].present?`, so the suite eager loads in CI. 3. Without CI, a test can call `Rails.application.eager_load!` inside `assert_nothing_raised`. For a single file, `Rails.autoloaders.main.cpath_expected_at("app/services/filings/deadline_calculator.rb")` in a console returns the constant path Zeitwerk expects. ## Reading a naming error When a deploy or a CI run stops with a `Zeitwerk::NameError`, the message already contains the fix. Work through it in this order: 1. **Find the expected constant.** The message says which constant Zeitwerk expected, for example `Filings::DeadlineCalculator`. That name comes from the path, never from the file's contents. 2. **Open the file and compare.** Typical mismatches are a missing namespace (`class DeadlineCalculator` with no `module Filings` around it), a typo, an acronym (`PDFExporter` where the path says `pdf_exporter`), or a file that defines two classes and neither matches. 3. **Decide which side moves.** Usually the class or the file is renamed. When the spelling of the constant is deliberate, an inflector override or a different directory layout (collapsing a grouping folder, ignoring a folder of scripts) is the alternative. 4. **Re-run `bin/rails zeitwerk:check`** until it prints "All is good!". Lazy loading in development hides these mistakes, which is why the eager-load check belongs in every pipeline, not only in production boots. ## Traps - **No `require` for autoloaded code.** Requiring an application file by hand works against the loader; `require_dependency` is a leftover from the classic autoloader. - **Zeitwerk is not a faster `require`.** In development it loads lazily, on first reference; it eager loads only where `config.eager_load` is true. - **New top-level folders need a restart.** The list of `app` subdirectories is fixed at boot.
- You create app/forms while bin/rails server is running. Why does a class in it stay undefined until a restart?The autoload paths are computed at boot from the `app` subdirectories that exist then, and that list is frozen when the loaders are set up. A brand-new top-level folder under `app` is not a root until the application boots again. New files inside an existing autoload path are a different case: in development the reloader picks them up.
- Why does app/models/concerns/stampable.rb define Stampable rather than Concerns::Stampable?Rails adds every `app/*/concerns` directory to the autoload paths, so `app/models/concerns` is a root directory in its own right. Zeitwerk treats nested roots as independent trees, so `concerns` is not a namespace inside `app/models`, and its files define top-level constants.
- How do you catch a misnamed file before it reaches production if development never loads it?Eager load somewhere other than production. A new app's `config/environments/test.rb` sets `config.eager_load = ENV["CI"].present?`, so CI loads every file. Locally, `bin/rails zeitwerk:check` does the same, and a test with `assert_nothing_raised { Rails.application.eager_load! }` works without CI.
- Zeitwerk is a faster require that loads every file at boot in every environment.
- app/services must be pushed to config.autoload_paths before Rails will load it.
- app/services/filings/deadline_calculator.rb should define Services::Filings::DeadlineCalculator.
- A file may define any constant as long as its name is unique in the app.
- If the app boots in development, production will boot the same way.
- Add require_dependency calls so application classes load in the right order.
Assumes Rails 8.1, where Zeitwerk is the only autoloader; Rails 7.0 removed classic mode and its underscore-based lookup.