skip to content

Initializers & Load Order

bin/rails loads config/boot.rb, config/application.rb and config/environment.rb, then the environment file and initializers in order. Interviewers ask where settings belong and when each hook runs.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In a Rails 8.1 app, what do config/boot.rb, config/application.rb and config/environment.rb each do at startup?

level: juniorimportance: must knowfreq 52%

answer

  1. boot.rb points at the Gemfile
  2. application.rb: frameworks, gems, the class
  3. Bundler.require(*Rails.groups)
  4. environment.rb calls initialize!
  5. initialize! runs only once

basics

~10 s

config/boot.rb makes the Gemfile's gems loadable. config/application.rb loads Rails, requires the app's gems and defines the Application class with its settings. config/environment.rb requires it and calls Rails.application.initialize!, which runs every initializer.

solid answer

~40 s

`config/boot.rb` points `BUNDLE_GEMFILE` at the app's Gemfile and requires `bundler/setup` (plus `bootsnap/setup` in a generated app), so the locked gems are loadable. `config/application.rb` requires `boot.rb`, loads the frameworks with `require "rails/all"` (or the chosen subset), requires the Gemfile's gems for the default and current-environment groups with `Bundler.require(*Rails.groups)`, and defines `MuseumTickets::Application < Rails::Application`, whose class body holds the shared configuration. `config/environment.rb` requires `application.rb` and calls `Rails.application.initialize!`, which runs the initializers: the environment file, the frameworks' initializers, `config/initializers/*.rb`, then the middleware build, eager loading and `after_initialize`. `bin/rails console` and `runner` load application then environment; the server reaches `environment.rb` through `config.ru`; the Rakefile loads only `application.rb` until a task depends on `:environment`.

code

ruby · 8 lines
ruby
# config/boot.rb
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
require "bundler/setup"
require "bootsnap/setup"

# config/environment.rb
require_relative "application"
Rails.application.initialize!

go deeper

for a junior

Recall the chain boot.rb, application.rb, environment.rb, what each one does, and that environment.rb is the file that actually initializes the app.

for a middle

Explain what Bundler.require(*Rails.groups) selects, why the class body runs before any initializer, and which entry points load application.rb only versus the full environment.

for a senior

Use the split when debugging boot: know what is unavailable in the application.rb class body, why Rake tasks need :environment, and why initialize! cannot be re-run.

for a principal

Keep boot predictable across a team: settings in the file whose phase matches them, scripts and tasks that load exactly as much of the app as they need.

## Three files, three jobs A Rails app starts in three small steps, each in its own file under `config/`. Each one requires the one before it, so loading the last one loads all three. | File | Job | Ends with | |---|---|---| | `config/boot.rb` | make the Gemfile's gems loadable | `bundler/setup` (and `bootsnap/setup`) required | | `config/application.rb` | load Rails and the gems, define the app class | `MuseumTickets::Application` defined and configured | | `config/environment.rb` | run the initialization process | `Rails.application.initialize!` finished | ## config/boot.rb The generated file sets `ENV["BUNDLE_GEMFILE"]` to the app's own Gemfile unless it is already set, requires `bundler/setup` so that only the versions locked in `Gemfile.lock` are on the load path, and, in a generated app, requires `bootsnap/setup` to cache expensive boot work. Nothing about Rails itself runs here. `bin/rails` requires this file first. ## config/application.rb This file turns a Ruby process into a Rails application definition: - `require_relative "boot"` runs the step above. - `require "rails/all"` loads every framework's railtie; an app generated with frameworks skipped gets `require "rails"` plus one line per framework instead. - `Bundler.require(*Rails.groups)` requires the gems from the Gemfile's `default` group and the group named after the current environment, plus any listed in `RAILS_GROUPS`. - `module MuseumTickets; class Application < Rails::Application` defines the app. Inheriting from `Rails::Application` registers the class as the app and runs `before_configuration` hooks, and the class body (`config.load_defaults`, `config.autoload_lib`, `config.time_zone` and so on) then executes immediately, top to bottom. At the end of this file the app is **defined and configured, but not initialized**: no initializer has run, the environment file has not been read and autoloading of `app/` is not set up yet. ## config/environment.rb and initialize! The generated file is two lines: `require_relative "application"` and `Rails.application.initialize!`. `initialize!` runs every initializer once, in dependency order: 1. **Bootstrap:** `config/environments/<env>.rb` is required first, then logger, cache and error reporter are set up, and `before_initialize` hooks run. 2. **Railties:** each framework and engine runs its initializers, and the application's own step loads `config/initializers/*.rb` in sorted order. 3. **Finisher:** the main autoloader is set up, the middleware stack is built, `to_prepare` callbacks run, code is eager loaded when `config.eager_load` is true, and `after_initialize` hooks run. A second call raises `Application has been already initialized.`; `Rails.application.initialized?` tells you whether it has happened. ## Who loads which file - `bin/rails` sets `APP_PATH` to `config/application` and requires `config/boot.rb`. Commands that need the app, such as `console`, `runner` and `routes`, then require `application.rb` and `environment.rb`. - `bin/rails server` starts the Rack server, which reads `config.ru`; that file requires `config/environment.rb`. - The `Rakefile` requires only `config/application.rb` and loads the tasks. A task that needs models declares `=> :environment`, and the `:environment` task requires `config/environment.rb`. ## What is available at each point | Where your code runs | Rails loaded | Gems required | Initializers run | `app/` autoloadable | |---|---|---|---|---| | `config/boot.rb` | no | no (only made loadable) | no | no | | `application.rb` class body | yes | yes | no | no | | `config/environments/<env>.rb` | yes | yes | no, it is the first step | no | | `config/initializers/*.rb` | yes | yes | frameworks' yes | no, reloadable classes raise `NameError` | | after `initialize!` returns | yes | yes | all | yes | The table explains most "it works in the console but not in my config" surprises: the console runs after `initialize!` returned, while the config file ran at one of the earlier rows. ## Practical consequences - Code in the `application.rb` class body runs before the environment file and before any initializer, so it cannot use anything initializers set up. - Settings that differ by environment belong in `config/environments/<env>.rb`, not in `environment.rb`, which only triggers initialization. - A script that needs the full app should require `config/environment`, not just `config/application`; `bin/rails runner` does this for you. - Because `initialize!` runs once per process, a change to any of these files or to `config/initializers` needs a restart; code reloading in development covers autoloaded code such as `app/`, not boot files.

  • In a Rails app, why does a Rake task that uses models need to depend on :environment?
    The Rakefile only requires `config/application.rb` and loads the tasks, so the app is defined but not initialized: no autoloading of `app/`, no database configuration applied. Depending on `:environment` runs that task first, which requires `config/environment.rb` and calls `initialize!`. For Rake, eager loading follows `config.rake_eager_load`, which is false by default.
  • In Rails 8.1, what happens if code calls Rails.application.initialize! a second time?
    It raises a `RuntimeError` with `Application has been already initialized.` Initialization runs each initializer exactly once per process; to apply changed configuration you restart the process. `Rails.application.initialized?` reports whether it has already happened.

  • config/boot.rb defines the Application class and holds its settings.
  • Production-only settings belong in config/environment.rb.
  • Calling Rails.application.initialize! again reloads changed configuration.
  • Bundler.require(*Rails.groups) requires test-group gems in production too.
  • Requiring config/application.rb alone makes app/models classes usable in a script.
open as a page

In Rails 8.1, how does RAILS_ENV select a config/environments file, and in what order do application.rb, that file and config/initializers apply?

level: middleimportance: must knowfreq 55%

basics

~20 s

Rails.env comes from RAILS_ENV, else RACK_ENV, else development, and only config/environments/<env>.rb is loaded. The application.rb class body runs first, then the environment file, then framework initializers, then config/initializers in sorted order; a later assignment overrides an earlier one.

open as a page

In Rails 8.1, how do config.x and Rails.application.config_for differ for app-specific settings, and what does each return when a value is missing?

level: middleimportance: should knowfreq 30%

basics

~10 s

config.x holds namespaced settings assigned in Ruby, such as config.x.ticketing.currency; an unset key reads nil. config_for(:ticketing) loads config/ticketing.yml, evaluates ERB and returns the current environment's section merged over shared; a missing file raises.

open as a page

In Rails 8.1, when do before_initialize, to_prepare and after_initialize blocks run, and which suits code that configures a reloadable class?

level: seniorimportance: should knowfreq 40%

basics

~20 s

before_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.

open as a page

In a Rails 8.1 museum-ticketing app, config/initializers/booking_limits.rb reads a flag set in feature_flags.rb and sees nil; why, and how would you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Files in config/initializers load in sorted path order, so booking_limits.rb runs before feature_flags.rb, and config.x returns nil for a key nobody has set yet. Set the flag in application.rb or the environment file, or read it later.

open as a page