skip to content

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%

answer

  1. config.x: two-level namespaces in Ruby
  2. unset key reads nil
  3. config_for reads config/<name>.yml
  4. environment section merged over shared
  5. missing file raises

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.

solid answer

~40 s

`config.x` is a namespace for your own settings: `config.x.ticketing.currency = "EUR"` in `application.rb` or an environment file, read as `Rails.configuration.x.ticketing.currency`. Each namespace is an `ActiveSupport::OrderedOptions`, created on first access, so an unset key returns `nil` and a bang reader such as `currency!` raises `KeyError` when the value is blank. Only two levels auto-create; deeper nesting needs an explicit Hash or OrderedOptions. `Rails.application.config_for(:ticketing)` reads `config/ticketing.yml`, runs ERB, takes the section for `Rails.env` (or the `env:` argument) and deep-merges it over a `shared` section. It returns an `ActiveSupport::OrderedOptions` with symbolized keys at the top level, while nested values are plain Hashes with symbol keys. A missing file raises; a missing environment section with no `shared` returns `nil`. A common pattern combines them: `config.x.ticketing = config_for(:ticketing)`.

code

ruby · 9 lines
ruby
Rails.configuration.x.ticketing.currency        # => "EUR"
Rails.configuration.x.ticketing.not_set         # => nil
Rails.configuration.x.ticketing.not_set!        # KeyError: :not_set is blank
Rails.configuration.x.ticketing.pricing.adult   # NoMethodError on nil

tickets = Rails.application.config_for(:ticketing)
tickets.currency                                # => "EUR"
tickets[:pricing][:adult]                       # => 2000
tickets[:pricing]["adult"]                      # => nil

go deeper

for a junior

Recall that config.x holds your own settings and that config_for loads a YAML file from config/ for the current environment.

for a middle

Explain what each returns for unset keys, how shared merges with the environment section, and why nested config_for values need symbol keys.

for a senior

Choose between them for maintainability, fail loudly on required values without tripping on false, and load YAML once in application.rb so initializers can rely on it.

for a principal

Decide which settings live in code, YAML, environment variables or credentials, so each value has one source and configuration does not drift between environments.

## Two homes for app-specific settings Rails gives an application two built-in ways to hold its own configuration, next to the framework settings: - **`config.x`**, a namespace for values assigned in Ruby, typically in `config/application.rb` or `config/environments/<env>.rb`; - **`Rails.application.config_for(name)`**, which loads a YAML file under `config/` and returns the part for the current environment. Both end up readable through `Rails.configuration`, which is the same object as `Rails.application.config`. ## config.x ```ruby # config/application.rb config.x.ticketing.currency = "EUR" config.x.ticketing.max_party_size = 8 ``` Read it anywhere after boot with `Rails.configuration.x.ticketing.max_party_size`. The mechanics: - `config.x` answers any method name with a namespace. The first read of `x.ticketing` creates an empty `ActiveSupport::OrderedOptions` and stores it. - An `OrderedOptions` returns `nil` for a key that was never assigned, so `x.ticketing.not_set` is `nil`. - A **bang reader**, `x.ticketing.currency!`, returns the value or raises `KeyError` (`:currency is blank`) when it is blank. `false` and empty strings are blank, so do not use it on booleans. - Only two levels auto-create. `x.ticketing.pricing.adult` calls `adult` on `nil` and raises `NoMethodError`, unless `pricing` was assigned a Hash-like value first. Single-level custom settings also work directly on `config`: `config.museum_name = "Rijks"` is readable as `Rails.configuration.museum_name`, but reading one that was never set raises `NoMethodError` instead of returning `nil`. ## config_for ```yaml # config/ticketing.yml shared: currency: EUR pricing: adult: 2000 development: pricing: child: 0 production: gateway_url: <%= ENV["TICKET_GATEWAY_URL"] %> ``` `Rails.application.config_for(:ticketing)` does five things: 1. Builds the path `config/ticketing.yml` (a `Pathname` argument is used as-is). 2. Raises `Could not load configuration. No such file - ...` if the file is missing. 3. Evaluates ERB, parses the YAML and deep-symbolizes every key. 4. Takes the section for `Rails.env`, or for `env:` when given, and **deep-merges it over `shared`**, so development above gets `pricing: { adult: 2000, child: 0 }`. 5. Returns an `ActiveSupport::OrderedOptions` when the result is a Hash, or `nil` when there is neither an environment section nor `shared`. Access follows from that: `config_for(:ticketing).currency` and `config_for(:ticketing)[:currency]` both work at the top level, and `["currency"]` works too because `OrderedOptions` converts keys to symbols. Nested values are plain Hashes with symbol keys, so it is `[:pricing][:adult]`; `[:pricing]["adult"]` is `nil`. ## Comparison | | `config.x` | `config_for` | |---|---|---| | Source | Ruby assignments | YAML with ERB under `config/` | | Per-environment values | separate assignments per environment file | one file, sections per environment plus `shared` | | Unset key | `nil` (bang reader raises) | top level `nil`; missing file raises | | Deep nesting | two levels auto-create | any depth, as plain Hashes below the top | ## Choosing between them - **A handful of values that vary little:** `config.x` assignments in `application.rb`, overridden in an environment file where needed. Everything stays in Ruby and is easy to grep. - **A block of structured data per environment:** a YAML file with `config_for`, where `shared` holds the defaults and each environment section only its differences. - **Values that come from the deployment:** read `ENV` inside the YAML through ERB, or in Ruby, rather than committing them. - **Required values:** read them with a bang reader at boot, or check them explicitly, so a missing value fails at startup instead of at the first request that needs it. Both are read-only conventions, not enforced types: nothing stops code from assigning `Rails.configuration.x.ticketing.currency` at runtime, so treat them as constants after boot. ## Using them together The common pattern loads the YAML once and exposes it under `config.x`: ```ruby config.x.ticketing = config_for(:ticketing) ``` Do this in `application.rb` so every initializer sees it, and read it everywhere else as `Rails.configuration.x.ticketing`. Keep secrets out of these files; use the encrypted credentials or environment variables for them. Because `config_for` returns plain Hashes below the top level, prefer symbol keys or `dig(:pricing, :adult)` in the code that reads nested values.

  • In Rails 8.1, how do you read another environment's section with config_for?
    Pass the `env:` keyword: `Rails.application.config_for(:ticketing, env: "production")` returns the production section merged over `shared`, whatever `Rails.env` is. It is useful in scripts and tests that need to inspect another environment's values without changing `RAILS_ENV`.
  • In Rails 8.1, what does config_for return when config/ticketing.yml has only a shared section?
    The `shared` section on its own, as an `ActiveSupport::OrderedOptions`. When the current environment's section is missing and `shared` is a Hash, Rails starts from an empty Hash and merges it over `shared`, so every environment gets the shared values.

  • config_for returns nil when the YAML file does not exist.
  • config.x creates nested namespaces to any depth on demand.
  • config_for's nested values can be read with string keys.
  • An unset config.x key raises NoMethodError.
  • config_for ignores the shared section whenever the environment section exists.