skip to content

In a Rails 8.1 app, config/initializers/exporters.rb registers ClauseRenderer from app/renderers in a registry; why does boot raise NameError, and what goes stale once it is forced to work?

level: seniorimportance: should knowfreq 35%

answer

  1. initializers run before the main loader
  2. reloading removes the constant
  3. registry keeps the old class object
  4. store the name, constantize later
  5. autoload_once_paths for cached classes

basics

~20 s

Initializers run before Rails sets up the main autoloader, so reloadable app classes cannot be referenced there. If forced in, the registry keeps the class object from boot, and after a reload it holds a stale class.

solid answer

~40 s

`config/initializers/*.rb` run once at boot, before Rails sets up `Rails.autoloaders.main`, so referencing a reloadable constant such as `ClauseRenderer` there raises `NameError` (Rails 7 made this an error). Forcing it in, for example by requiring the file, makes the registry hold the class object from boot. In development a reload removes the `ClauseRenderer` constant and autoloads a new class, but the registry still points at the old one, so edits do nothing and `is_a?` checks against the new class fail. Fixes: re-register inside `Rails.application.config.to_prepare`, which runs at boot and after every reload and must be idempotent; store the name `"ClauseRenderer"` and `constantize` it when used; or, if the class must live somewhere that never reloads, make it non-reloadable with `config.autoload_once_paths` or `config.autoload_lib_once`.

code

ruby · 11 lines
ruby
# config/initializers/exporters.rb
CLAUSE_RENDERERS = {}

# NameError at boot: the main autoloader is not set up yet.
# CLAUSE_RENDERERS[:indemnity] = ClauseRenderer

# Runs at boot and after every reload, so the registry
# always holds the current class object.
Rails.application.config.to_prepare do
  CLAUSE_RENDERERS[:indemnity] = ClauseRenderer
end

go deeper

for a junior

Remember not to reference app classes directly in config/initializers, and to rebuild objects after reload! in the console.

for a middle

Explain why initializers cannot autoload from the main loader and how unloading a constant leaves old references pointing at an old class.

for a senior

Pick the right fix per case: to_prepare with idempotent code, configuring names instead of classes, or moving code to autoload_once_paths, and find stale holders quickly.

for a principal

Set the team rule that boot-time code never caches reloadable classes, and shape extension points so they take names rather than class objects.

## The scenario A legal-documents app renders contract clauses through a small registry, a hash constant defined in an initializer. Someone writes: ```ruby # config/initializers/exporters.rb CLAUSE_RENDERERS = {} CLAUSE_RENDERERS[:indemnity] = ClauseRenderer ``` `ClauseRenderer` lives in `app/renderers/clause_renderer.rb`. Boot fails with `NameError: uninitialized constant ClauseRenderer`. A colleague "fixes" it by requiring the file by its full path, boot succeeds, and then developers find that editing `ClauseRenderer` changes nothing until they restart the server. ## Why the initializer cannot see the class Rails sets up the **main** autoloader, which manages the autoload paths under `app` and `lib`, in an initializer of its own that runs **after** the files in `config/initializers` have run. During those files the autoloads for application constants do not exist yet, so a reference to `ClauseRenderer` is an ordinary missing constant. Since Rails 7 this is a hard `NameError`. The rule is deliberate. Initializers run **once**; they do not run again on reload. Any reloadable class captured during boot would go stale on the first reload, so Rails refuses the reference outright. The **once** autoloader is the exception: it is set up early (before `:bootstrap_hook`), so classes in `config.autoload_once_paths` can be autoloaded from initializers. ## What goes stale, and why Ruby has no way to swap a class everywhere it is referenced. When Rails reloads, it **removes** the constants the main loader autoloaded, and the next reference autoloads a brand-new class object. Anything that kept a reference to the old object keeps it: - a registry, a hash or a class-level variable filled at boot; - **instances** built before the reload: in a console, `old = Filing.new; reload!; old.class == Filing` is `false`; - a class in a non-reloaded place that **subclasses** a reloadable one, such as `class VipClause < ClauseRenderer` in code loaded once: its superclass stays the old class object; - framework places that hold class objects: the middleware stack, framework configuration such as custom serializers, modules mixed into framework classes. Symptoms are confusing: edits "do nothing", and `is_a?(ClauseRenderer)` returns false for objects that clearly are clause renderers, because they belong to the old class object that still carries the same name. ## Fixes, by situation | Situation | Fix | |---|---| | Code must run at boot and again after each reload | wrap it in `Rails.application.config.to_prepare do ... end` | | A library or engine needs a class from the app | configure the **name** (`"ClauseRenderer"`) and call `constantize` when it is used | | The object lives somewhere that never reloads | make it non-reloadable: `config.autoload_once_paths`, `config.autoload_lib_once`, or `lib` plus `require` and an ignore entry | | A boot-time check only | `config.after_initialize` can autoload, but whatever it captures goes stale after a reload | Notes on each: 1. **`to_prepare`** runs on boot and after every reload, so the registry is refilled with the current class. Rails warns that it may run twice, so the block must be **idempotent**: assigning the same hash key again replaces the entry, which is safe; appending to a list would not be. 2. **Names instead of objects** are how engines accept app classes: the engine stores a string and resolves it at call time, so it always gets the current class. 3. **Non-reloadable code** is the honest answer for middleware and framework decorations. A class in `config.autoload_once_paths` is autoloaded but never unloaded, so there is nothing to go stale; edits to it simply require a restart. ## Middleware and framework decorations Some places hold class objects by design, and those classes should not be reloadable at all: - **The middleware stack.** `config.middleware.use Paperwork::AuditTrail` stores the class when the stack is built; reloading never rebuilds the stack, so a reloadable middleware would silently keep running old code. - **Modules mixed into framework classes.** A module included into `ActiveRecord::Base` through an `on_load` hook becomes part of that class's ancestor chain; a reloaded copy of the module would never replace the one already in the chain. - **Framework configuration that takes classes.** A setting such as a list of serializers keeps whatever object was pushed into it at boot. For these, the Rails guide recommends either putting the code in `lib`, loading it with an explicit `require` and adding the folder to the `autoload_lib` ignore list, or placing the directory in `config.autoload_once_paths`. Both make the code load once and stay put, which matches how it is used. ## How to spot it - In development, edits to one class need a restart while others reload: something holds the old object. - `Rails.autoloaders.log!` in `config/application.rb` traces what the loaders load and unload. - Search initializers and `lib` for application class names used as values rather than as strings. Bottom line from the Rails guide: **do not cache reloadable classes or modules**.

  • Why does a class in config.autoload_once_paths work in an initializer when one in app/models does not?
    The `once` autoloader is set up early in boot, before `:bootstrap_hook`, so its autoloads exist when initializers run. Its classes are never unloaded, so a reference captured at boot never goes stale. The price is that editing such a class needs a restart, even in development.
  • After reload! in a console, why does filing.is_a?(Filing) return false for an object built earlier?
    `reload!` removed the `Filing` constant and the next reference autoloaded a new class object. The old instance still belongs to the old class, so it is not an instance of the new one. Rebuild the object, or start a new console session, after reloading.
  • How should an engine let the host app configure which user class it works with?
    Accept the class name as a string, for example `config.user_model = "User"`, and call `constantize` on it at the moment it is needed. Assigning the class object in an initializer raises `NameError` at boot, and even if forced, it would go stale after the first reload.

  • Rails patches the existing class object in place when a file changes.
  • Initializers run again after every code reload in development.
  • Requiring the file in the initializer is the clean fix for the NameError.
  • Stale classes are only a console problem and never affect the server.
  • Putting the class in autoload_once_paths makes it reload on every edit.

Assumes Rails 8.1 with Zeitwerk; since Rails 7, referring to a reloadable constant while the app boots raises NameError instead of working.