skip to content

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%

answer

  1. RAILS_ENV, then RACK_ENV, then development
  2. only <env>.rb is required
  3. class body before any initializer
  4. environment file loads first in initialize!
  5. config/initializers after framework initializers

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.

solid answer

~40 s

`Rails.env` is `RAILS_ENV`, falling back to `RACK_ENV` and then to `"development"`, wrapped so that `Rails.env.production?` works. Only `config/environments/#{Rails.env}.rb` is required; the others are never read. The order is fixed: the `config/application.rb` class body runs when the file is required, then `initialize!` requires the environment file as its very first initializer, then `before_initialize` hooks, then each framework's and engine's initializers, then `config/initializers/*.rb` in sorted path order, then the finisher steps. Because each step can reassign `config`, **later wins**: the environment file overrides `application.rb`, and an initializer can override both. Shared defaults go in `application.rb`, per-environment differences in the environment file, and code that configures gems or objects in `config/initializers`. Some settings are consumed before your initializers run, so setting them there is too late.

code

ruby · 12 lines
ruby
# config/application.rb
module MuseumTickets
  class Application < Rails::Application
    config.log_level = :info
    config.x.ticketing.max_party_size = 8
  end
end

# config/environments/development.rb
Rails.application.configure do
  config.log_level = :debug
end

go deeper

for a junior

Recall that RAILS_ENV picks one file in config/environments and that development is the default when nothing is set.

for a middle

Explain the order application.rb, environment file, framework initializers, config/initializers, and that the last assignment wins, with an example of an override.

for a senior

Spot settings that are consumed before initializers run, and debug a wrong value by checking which phase last assigned it and whether the environment file exists.

for a principal

Keep environments few and close to production, and give each kind of setting one documented home so overrides do not spread across files.

## Choosing the environment `Rails.env` is computed once from the process environment: `ENV["RAILS_ENV"]` if present, otherwise `ENV["RACK_ENV"]`, otherwise `"development"`. The value is an `ActiveSupport::EnvironmentInquirer`, a string that also answers predicates such as `Rails.env.production?` or `Rails.env.staging?`. The application's path configuration registers `config/environments` with the glob `"#{Rails.env}.rb"`. During initialization Rails requires **only the file matching the current environment**. A new app has three: `development.rb`, `test.rb` and `production.rb`. Adding `config/environments/staging.rb` (usually starting from a copy of `production.rb`) and booting with `RAILS_ENV=staging` creates a fourth environment. If the file for the current environment does not exist, that step simply loads nothing: the app boots with whatever `application.rb` and the initializers set. ## The order settings are applied 1. **`config/application.rb` class body.** It executes when the file is required, before `initialize!` starts. Everything shared by all environments goes here. 2. **`config/environments/<env>.rb`.** `initialize!` runs the `load_environment_config` initializer first, ahead of the rest of bootstrap. 3. **`before_initialize` hooks**, at the end of the bootstrap phase. 4. **Framework and engine initializers.** Active Record, Action Mailer and the rest read the configuration and set themselves up. 5. **`config/initializers/*.rb`**, loaded by the app's `load_config_initializers` step, every file under the folder sorted by path. 6. **Finisher:** autoloader setup, middleware build, `to_prepare`, eager loading, `after_initialize`. Each step can assign the same `config` keys, so **the last assignment wins**. If `application.rb` sets `config.log_level = :info` and `development.rb` sets `:debug`, development logs at `:debug`. ## A worked override chain Suppose the museum-ticketing app sets the same key in three places: - `application.rb`: `config.x.ticketing.max_party_size = 8` - `config/environments/production.rb`: `config.x.ticketing.max_party_size = 6` - `config/initializers/group_bookings.rb`: `Rails.application.config.x.ticketing.max_party_size = 10` In production the value ends as `10`, in development as `10` too, because the initializer runs last everywhere. Code that read the value earlier, for example inside the environment file, saw `6` or `8`. That is why one setting should have **one home**: the reader's result depends on when it reads, not only on the final value. ## Where each setting belongs | Kind of setting | Home | |---|---| | Same in every environment | `config/application.rb` | | Differs per environment | `config/environments/<env>.rb` | | Configures a gem, library or Ruby object | a file in `config/initializers/` | | Structured per-environment data | a YAML file read with `config_for` | | App-specific values read elsewhere | `config.x.<namespace>.<key>` in one of the first two | ## Settings consumed before your initializers run An initializer runs late, after the frameworks have already read part of the configuration. Some values are frozen or consumed by then: - `config.autoload_paths` is frozen before the bootstrap hook, so appending to it from `config/initializers` raises `FrozenError`. - A `config.before_initialize` block registered from `config/initializers` runs at once, because that phase has already passed. - Values that bootstrap uses, such as the logger and cache store settings, need to be set in `application.rb` or the environment file to take effect during bootstrap. The middleware stack, by contrast, is built in the finisher phase, so `config.middleware` calls in an initializer still apply. ## Custom environments A staging environment is a file plus a variable: 1. Create `config/environments/staging.rb`, usually starting from `production.rb`; it opens with `Rails.application.configure do`, like the generated ones. 2. Boot with `RAILS_ENV=staging`; `Rails.env.staging?` now returns true. 3. Add a `staging` entry wherever per-environment configuration lives outside this file, such as the database configuration and any YAML read with `config_for`; each of those is keyed by the environment name and does not fall back to production. Keep the number of environments small. Every extra one is another column of settings that can drift from production; a staging deploy that runs with `RAILS_ENV=production` and different environment variables is often the simpler choice. ## Reading the result - `Rails.env` and `Rails.env.production?` tell you which file was loaded. - `Rails.configuration` returns the same object as `Rails.application.config`, after all steps have run, which is the value the app actually uses. - `bin/rails initializers` prints the initializer names in run order, with the config files grouped under the single `load_config_initializers` entry.

  • In a Rails 8.1 app, what happens if RAILS_ENV=staging but config/environments/staging.rb does not exist?
    The environment-file step loads nothing and raises nothing, so the app boots with only `application.rb` and initializer settings, which usually means development-like defaults where production values were intended. Anything else keyed by environment, such as a database configuration entry, still needs its own `staging` section.
  • In Rails 8.1, why can an initializer still add middleware with config.middleware but not extend config.autoload_paths?
    The middleware stack is built in the finisher phase, after every file in `config/initializers` has run, so recorded `config.middleware` calls are still replayed. The autoload paths are frozen earlier, before the bootstrap hook, so appending to them from an initializer raises `FrozenError`.

  • Rails reads every file in config/environments and merges them.
  • application.rb settings override the environment file because they are the main configuration.
  • With no RAILS_ENV set, a Rails app defaults to production.
  • config/initializers run before the environment file, so they hold the defaults.
  • A missing config/environments/staging.rb makes the staging boot fail immediately.