In Rails 8.1, when do before_initialize, to_prepare and after_initialize blocks run, and which suits code that configures a reloadable class?
answer
- bootstrap, then initializers, then finisher
- before_initialize at the bootstrap hook
- to_prepare: boot plus every reload
- after_initialize: last, once
- initializers cannot autoload app/ classes
basics
~20 sbefore_initialize runs at the end of bootstrap, before framework and app initializers. to_prepare runs once at boot, before eager loading, and again after every code reload. after_initialize runs last, once. Code that configures a reloadable class belongs in to_prepare.
solid answer
~50 s`config.before_initialize` blocks run at the `bootstrap_hook`, after the environment file and before the framework initializers and `config/initializers`; registered from an initializer, the block runs immediately, because that point has passed. `config.to_prepare` blocks are attached to the reloader in the finisher phase, run once at boot after the middleware stack is built and before eager loading, and run again after each code reload in development. `config.after_initialize` blocks run at the very end, after eager loading, once per boot. In Rails 8.1, as since 7.0, a plain initializer cannot reference a reloadable constant from `app/`: it raises `NameError`. So `TicketPrice.currency = ...` goes in a `to_prepare` block, which re-applies it to the fresh class after each reload; it must be idempotent. `after_initialize` suits one-time checks, but a value set there on a reloadable class is lost at the next reload.
code
ruby · 9 lines# config/initializers/ticket_pricing.rb
Rails.application.config.to_prepare do
# TicketPrice lives in app/models and is reloadable in development
TicketPrice.currency = Rails.configuration.x.ticketing.currency
end
Rails.application.config.after_initialize do
Rails.logger.info("Ticketing currency: #{Rails.configuration.x.ticketing.currency}")
endgo deeper
Recall the three hooks by name and that to_prepare is the one that runs again when code reloads in development.
Explain where each hook sits in the boot sequence and why plain initializers cannot reference reloadable classes from app/.
Choose hooks deliberately: to_prepare for reloadable classes and idempotent setup, after_initialize for one-time checks, and before_initialize only from application.rb or an environment file.
Keep boot-time code small and explicit across the codebase, so reload behaviour in development matches production and hooks never hide ordering dependencies.
## Three phases, several hooks `Rails.application.initialize!` runs its initializers in three groups: **bootstrap**, then the **railties** (every framework, engine and the app itself, including `config/initializers`), then the **finisher**. The configuration hooks let your code run at fixed points in that sequence without writing a railtie. | Hook | Runs | How often | |---|---|---| | `config.before_configuration` | when the app class inherits `Rails::Application`, before its class body | once | | `config.before_initialize` | at `bootstrap_hook`, after the environment file, before framework initializers | once | | `config.to_prepare` | finisher, after the middleware build, before eager loading | at boot and after each reload | | `config.before_eager_load` | finisher, just before eager loading, only if `config.eager_load` | once | | `config.after_initialize` | finisher, last, after eager loading | once | ## The timeline in order 1. `config/application.rb` class body runs. 2. `initialize!` requires `config/environments/<env>.rb`. 3. Bootstrap sets up the logger, cache, error reporter and the once-autoloader, then runs **`before_initialize`** blocks. 4. Framework and engine initializers run, then `config/initializers/*.rb` in sorted order. 5. The finisher sets up the main autoloader for `app/`, builds the middleware stack, registers and runs the **`to_prepare`** blocks, runs **`before_eager_load`** and eager loads when enabled, then runs **`after_initialize`** blocks. ## Why to_prepare exists: reloadable classes Classes under `app/` are managed by the main autoloader and are **reloadable** in development. Initializers run once, so if one stored settings on such a class, the next reload would replace the class and lose them. Rails therefore refuses: a plain initializer that references a reloadable constant raises `NameError`, because the main autoloader is not set up until the finisher. `to_prepare` solves it. The block runs at boot, after the main autoloader is ready, and the reloader runs it again after every reload, so the fresh class is configured too: - in development, after each request-time reload triggered by changed files; - in test and production, once at boot, because reloading is off. The block may run more than once, so it must be **idempotent**: assigning a value is fine, appending to an array on every run is not. ## When to use each hook - **`before_initialize`:** code that must run before frameworks initialize. Register it in `config/application.rb` or the environment file. A `before_initialize` block registered from `config/initializers` runs at once, because the bootstrap hook has already fired, so it is not really "before" anything. - **`to_prepare`:** configuring reloadable classes, such as setting a class attribute on a model or re-registering an `app/` class with a library after each reload. - **`after_initialize`:** work that needs the fully booted app exactly once, such as logging the effective configuration or a preflight check. Remember that Rake tasks depending on `:environment` boot the app too, so a check that aborts can block tasks such as seeding. It may autoload reloadable classes, but anything it stores on them is lost at the next reload in development. - **Plain initializer code:** configuring gems and objects that are not reloadable, such as a client built from `lib/` or a third-party library's settings. ## Inspecting the sequence - `bin/rails initializers` prints every initializer in run order; `bootstrap_hook`, `add_to_prepare_blocks`, `run_prepare_callbacks`, `eager_load!` and `finisher_hook` mark where the hooks fire. - A `Rails.logger.info` line inside each hook shows the actual order at boot, and in development a second `to_prepare` line appears after you edit a file under `app/` and send a request. - `Rails.application.initialized?` is false inside every hook except code that runs after `initialize!` returns, such as the console. ## Common mistakes - Setting `TicketPrice.currency` in `after_initialize`: works at boot, then the class is reloaded in development and the value is gone. - Registering `before_initialize` from an initializer and expecting it to run before Active Record initializes. - Writing a `to_prepare` block that appends a subscriber each time, which duplicates it after every reload. - Expecting `to_prepare` before every request: it runs only when a reload actually happened.
- In Rails 8.1, what happens to a config.before_initialize block registered inside config/initializers/museum.rb?It runs immediately. The hook is an Active Support load hook, and the `before_initialize` hooks already fired at the end of bootstrap, before `config/initializers` were loaded. A late registration for an already-run hook executes at once, so the block runs after the framework initializers, not before them.
- In Rails 8.1 production, does a to_prepare block run before or after eager loading, and how often?Before. The finisher runs the prepare callbacks, then eager loads when `config.eager_load` is true, then runs `after_initialize`. With reloading disabled, as in the generated `production.rb`, no reload ever happens, so the block runs once per boot.
- to_prepare blocks run before every request in development.
- after_initialize is the right place to set attributes on a reloadable model class.
- A before_initialize block in config/initializers runs before Active Record initializes.
- Initializers can reference app/models classes directly; Rails autoloads them.
- to_prepare runs after eager loading in production.
Assumes Rails 8.1; since Rails 7.0 an initializer that references a reloadable constant raises NameError, which is why to_prepare is the hook for reloadable classes.