Configuration files

suggest change

Most programs need settings that change between machines and deployments: ports, database hosts, log levels, feature flags, API keys. Ruby has YAML (psych) and JSON (json) in the standard library, and gems cover TOML and .env files.

This article shows how to read each format, the traps in each one, and how to build a small loader that layers defaults, a config file, per-environment sections and environment variables, then validates the result into immutable objects. For environment variables themselves see ENV, for the JSON API see JSON with Ruby, and for templates see ERB.

The examples were run with Ruby 4.0 (psych 5.3, json 2.18), tomlrb 3.0 and dotenv 3.2.

YAML

YAML is the usual choice in the Ruby world (Rails, RuboCop, GitHub Actions and Docker Compose all use it). It supports comments, nesting and lists, and it's easy for people to edit:

# config.yml
app_name: Bookshelf
port: 4567
debug: false
timeout: 2.5
admins:
  - alice
  - bob
database:
  host: localhost
  name: bookshelf
  pool: 5

YAML.load_file parses the file into plain Ruby objects: a Hash, Strings, Integers, Floats, booleans, Arrays and nil:

require 'yaml'

config = YAML.load_file('config.yml')
p config.class
p config['app_name']
p config['port']
p config['debug']
p config['timeout']
p config['admins']
p config['database']
p config.dig('database', 'pool')
Hash
"Bookshelf"
4567
false
2.5
["alice", "bob"]
{"host" => "localhost", "name" => "bookshelf", "pool" => 5}
5

Keys are Strings. Pass symbolize_names: true to get Symbol keys at every level:

require 'yaml'

config = YAML.load_file('config.yml', symbolize_names: true)
p config[:database]
p config.dig(:database, :host)
{host: "localhost", name: "bookshelf", pool: 5}
"localhost"

Loading is safe by default

Since Psych 4 (Ruby 3.1), YAML.load and YAML.load_file work like YAML.safe_load. They only build basic types. Any other class raises Psych::DisallowedClass, which stops a malicious file from creating arbitrary Ruby objects. Even Date and Symbol values have to be allowed explicitly:

require 'yaml'

yaml = <<~YAML
  released: 2026-10-17
  mode: :fast
YAML

begin
  YAML.load(yaml)
rescue Psych::DisallowedClass => e
  puts "#{e.class}: #{e.message}"
end

data = YAML.load(yaml, permitted_classes: [Date, Symbol])
p data
p data['released'].class
Psych::DisallowedClass: Tried to load unspecified class: Date
{"released" => #<Date: 2026-10-17 ((2461331j,0s,0n),+0s,-Infj)>, "mode" => :fast}
Date

YAML.unsafe_load and YAML.unsafe_load_file still exist. Never use them on files that someone else could have written.

Implicit typing traps

YAML guesses the type of unquoted values, and sometimes it guesses wrong:

require 'yaml'

yaml = <<~YAML
  version: 1.10
  zip: 01234
  country: NO
  answer: yes
  quoted_version: "1.10"
  quoted_zip: "01234"
  quoted_country: "NO"
  empty:
  tilde: ~
YAML

YAML.load(yaml).each { |k, v| puts "#{k.ljust(15)} #{v.inspect}" }
version         1.1
zip             668
country         false
answer          true
quoted_version  "1.10"
quoted_zip      "01234"
quoted_country  "NO"
empty           nil
tilde           nil

1.10 becomes the Float 1.1. 01234 is read as an octal number. Psych follows YAML 1.1, so yes, no, on, off (in any case) are booleans and Norway's country code turns into false. Quote any value that must stay a String: version numbers, zip codes, phone numbers, country codes and passwords.

Environments with anchors and merge keys

A common layout puts shared settings under one key and each environment under its own key. An anchor (&default) names a node, an alias (*default) refers to it, and the merge key << copies its entries into the current mapping:

# environments.yml
default: &default
  adapter: postgresql
  host: localhost
  pool: 5

development:
  <<: *default
  database: app_dev

test:
  <<: *default
  database: app_test

production:
  <<: *default
  host: db.internal
  pool: 20
  database: app_prod

Aliases are off by default, because a file with nested aliases can expand into a huge structure (the "billion laughs" attack). Turn them on with aliases: true for files you trust:

require 'yaml'

begin
  YAML.load_file('environments.yml')
rescue Psych::AliasesNotEnabled => e
  puts "#{e.class}: #{e.message}"
end

all = YAML.load_file('environments.yml', aliases: true)
p all['development']
p all['production']
Psych::AliasesNotEnabled: Alias parsing was not enabled. To enable it, pass `aliases: true` to `Psych::load` or `Psych::safe_load`.
{"adapter" => "postgresql", "host" => "localhost", "pool" => 5, "database" => "app_dev"}
{"adapter" => "postgresql", "host" => "db.internal", "pool" => 20, "database" => "app_prod"}

Keys written after << override the merged ones. The merge is shallow, though. If production defines its own database: mapping, that mapping replaces the default one completely, and nested keys aren't combined. The loader below fixes this with a deep merge.

ERB in YAML

Rails runs config/database.yml through ERB before parsing it, so values can come from environment variables. You can do the same thing yourself:

# db.yml
production:
  host: <%= ENV.fetch('DB_HOST', 'localhost') %>
  pool: <%= ENV.fetch('DB_POOL', 5).to_i %>
  password: <%= ENV['DB_PASSWORD'] %>
require 'yaml'
require 'erb'

ENV['DB_HOST'] = 'db.internal'
ENV['DB_PASSWORD'] = 's3cret'

text = ERB.new(File.read('db.yml')).result
puts text
p YAML.safe_load(text)
# db.yml
production:
  host: db.internal
  pool: 5
  password: s3cret
{"production" => {"host" => "db.internal", "pool" => 5, "password" => "s3cret"}}

ERB pastes text into the YAML before it's parsed, so a value containing : or # breaks the file or gets cut off. A JSON string is also a valid YAML string, so to_json gives you safe quoting:

require 'yaml'
require 'erb'
require 'json'

ENV['DB_PASSWORD'] = 'p@ss: #1'

bad  = ERB.new("password: <%= ENV['DB_PASSWORD'] %>").result
good = ERB.new("password: <%= ENV['DB_PASSWORD'].to_json %>").result
begin
  YAML.safe_load(bad)
rescue Psych::SyntaxError => e
  puts e.message
end
puts good
p YAML.safe_load(good)
(<unknown>): mapping values are not allowed in this context at line 1 column 15
password: "p@ss: #1"
{"password" => "p@ss: #1"}

ERB runs arbitrary Ruby code, so only use it on config files that are part of your application, never on files supplied by users.

JSON

JSON is a good fit when a config file is generated or edited by other tools, because every language can read and write it. JSON.load_file reads and parses a file in one call:

{
  "app_name": "Bookshelf",
  "port": 4567,
  "database": { "host": "localhost", "pool": 5 }
}
require 'json'

config = JSON.load_file('config.json', symbolize_names: true)
p config
p config.dig(:database, :pool)
{app_name: "Bookshelf", port: 4567, database: {host: "localhost", pool: 5}}
5

Strict JSON has no comments. Ruby's parser accepts // and /* */ comments anyway, which helps with hand-edited files:

require 'json'

text = <<~JSON
  {
    // the port to listen on
    "port": 4567,
    /* the pool size */
    "pool": 5
  }
JSON
p JSON.parse(text)
{"port" => 4567, "pool" => 5}

A trailing comma after the last entry is still a JSON::ParserError unless you pass allow_trailing_comma: true. Other tools that read the same file may reject comments, so use them only in files that nothing but Ruby reads.

TOML

TOML has explicit types (strings are always quoted, and dates are real dates), so it avoids the YAML guessing problems. Cargo, pyproject.toml and many CLI tools use it. Ruby doesn't ship a TOML parser. tomlrb is a small, fast, read-only one (gem install tomlrb):

# config.toml
title = "Bookshelf"
started = 2026-10-17T09:30:00Z
version = "1.10"
zip = "01234"

[server]
host = "0.0.0.0"
port = 4567
allowed_origins = ["https://example.com", "https://admin.example.com"]

[database]
host = "localhost"
pool = 5

[[workers]]
name = "mailer"
threads = 2

[[workers]]
name = "indexer"
threads = 4
require 'tomlrb'

config = Tomlrb.load_file('config.toml', symbolize_keys: true)
p config[:title]
p config[:started]
p config[:started].class
p config[:server]
p config[:workers]
p config[:workers].sum { _1[:threads] }
"Bookshelf"
2026-10-17 09:30:00 +0000
Time
{host: "0.0.0.0", port: 4567, allowed_origins: ["https://example.com", "https://admin.example.com"]}
[{name: "mailer", threads: 2}, {name: "indexer", threads: 4}]
6

[table] headers create nested hashes, and [[array]] headers append a hash to an array. If you also need to write TOML files, use the toml-rb gem, which can both parse and dump.

.env files and the dotenv gem

Twelve-factor apps read their configuration from environment variables. During development it's convenient to keep those variables in a .env file. The dotenv gem (gem install dotenv) loads that file into ENV:

# .env - local development settings, never commit this file
DATABASE_URL=postgres://localhost/app_dev
SECRET_KEY_BASE=dev-only-secret
PORT=4567
GREETING="Hello, ${USER_NAME}!"
require 'dotenv'

ENV['USER_NAME'] = 'Alice'
ENV['PORT'] = '3001' # pretend the shell already set it

Dotenv.load # reads .env; never overrides variables that are already set

p ENV['DATABASE_URL']
p ENV['SECRET_KEY_BASE']
p ENV['PORT']
p ENV['GREETING']

Dotenv.overwrite('.env.local') # this one does override
p ENV['PORT']

begin
  Dotenv.require_keys('DATABASE_URL', 'REDIS_URL')
rescue Dotenv::MissingKeys => e
  puts "#{e.class}: #{e.message}"
end
"postgres://localhost/app_dev"
"dev-only-secret"
"3001"
"Hello, Alice!"
"9292"
Dotenv::MissingKeys: Missing required configuration key: ["REDIS_URL"]

Here .env.local contains just PORT=9292. Real environment variables win over the file, so production can set them normally and the .env file only fills in what's missing. ${VAR} inside double quotes is expanded. When you pass several files, the first file that sets a variable wins, so list the most specific file first:

require 'dotenv'

Dotenv.load('.env.local', '.env') # the first file that sets a variable wins
p ENV['PORT']
p ENV['DATABASE_URL']
"9292"
"postgres://localhost/app_dev"

require 'dotenv/load' loads .env as a side effect of the require, and the dotenv-rails gem hooks into Rails boot. Add .env and .env.local to .gitignore, and commit a .env.example that lists the variable names with dummy values.

Layering defaults, file and environment

Real applications usually combine several sources. Later sources override earlier ones:

  1. defaults in code
  2. the section of the config file for the current environment
  3. environment variables, for secrets and per-deployment overrides
# app.yml
default: &default
  port: 4567
  log_level: info
  database:
    host: localhost
    pool: 5

development:
  <<: *default
  log_level: debug

production:
  <<: *default
  database:
    host: db.internal
    pool: 20
# settings.rb
require 'yaml'

module Settings
  DEFAULTS = {
    'port' => 8000,
    'log_level' => 'warn',
    'database' => { 'host' => 'localhost', 'pool' => 5, 'timeout' => 5.0 }
  }.freeze

  # ENV variable => path of keys in the config hash, plus a converter
  ENV_OVERRIDES = {
    'APP_PORT' => [%w[port], :Integer],
    'APP_LOG_LEVEL' => [%w[log_level], :String],
    'DB_HOST' => [%w[database host], :String],
    'DB_POOL' => [%w[database pool], :Integer]
  }.freeze

  def self.deep_merge(a, b)
    a.merge(b) do |_key, old, new|
      old.is_a?(Hash) && new.is_a?(Hash) ? deep_merge(old, new) : new
    end
  end

  def self.load(path, env: ENV.fetch('APP_ENV', 'development'))
    all = File.exist?(path) ? YAML.load_file(path, aliases: true) || {} : {}
    from_file = all.fetch(env) { raise KeyError, "no '#{env}' section in #{path}" }

    from_env = {}
    ENV_OVERRIDES.each do |var, (keys, type)|
      next unless ENV.key?(var)
      value = Kernel.send(type, ENV[var])
      *parents, last = keys
      parents.inject(from_env) { |h, k| h[k] ||= {} }[last] = value
    end

    deep_merge(deep_merge(DEFAULTS, from_file), from_env)
  end
end

Environment variables are always Strings, so each override names a converter. Kernel#Integer is strict: unlike "abc".to_i, which quietly returns 0, it raises on bad input:

require_relative 'settings'

p Settings.load('app.yml')
p Settings.load('app.yml', env: 'production')

ENV['DB_POOL'] = '50'
ENV['APP_PORT'] = '9000'
p Settings.load('app.yml', env: 'production')

ENV['APP_PORT'] = 'abc'
begin
  Settings.load('app.yml')
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end

begin
  Settings.load('app.yml', env: 'staging')
rescue KeyError => e
  puts "#{e.class}: #{e.message}"
end
{"port" => 4567, "log_level" => "debug", "database" => {"host" => "localhost", "pool" => 5, "timeout" => 5.0}}
{"port" => 4567, "log_level" => "info", "database" => {"host" => "db.internal", "pool" => 20, "timeout" => 5.0}}
{"port" => 9000, "log_level" => "info", "database" => {"host" => "db.internal", "pool" => 50, "timeout" => 5.0}}
ArgumentError: invalid value for Integer(): "abc"
KeyError: no 'staging' section in app.yml

The database mapping from the file has no timeout key. The deep merge keeps host and pool from the file and takes timeout from DEFAULTS. A plain merge would have replaced the whole database hash and lost timeout.

Validating into immutable objects

A Hash of Strings is easy to misuse. A typo such as config['prot'] silently returns nil, and invalid values only show up deep inside the program. Converting the merged hash into Data objects (Ruby 3.2+) at startup gives you required keys, rejected unknown keys, validated values, reader methods and frozen objects:

require_relative 'settings'

LOG_LEVELS = %w[debug info warn error].freeze
DatabaseConfig = Data.define(:host, :pool, :timeout) do
  def initialize(host:, pool:, timeout: 5.0)
    raise ArgumentError, "database.pool must be 1..100, got #{pool}" unless (1..100).cover?(pool)
    super
  end
end

AppConfig = Data.define(:port, :log_level, :database) do
  def self.from_hash(h)
    h = h.transform_keys(&:to_sym)
    unknown = h.keys - members
    raise ArgumentError, "unknown config keys: #{unknown.join(', ')}" if unknown.any?
    new(**h, database: DatabaseConfig.new(**h.fetch(:database).transform_keys(&:to_sym)))
  end

  def initialize(port:, log_level:, database:)
    raise ArgumentError, "log_level must be one of #{LOG_LEVELS.join('/')}" unless LOG_LEVELS.include?(log_level)
    super
  end
end

config = AppConfig.from_hash(Settings.load('app.yml', env: 'production'))
p config.port
p config.database.host
p config.database
p config.frozen?

begin
  AppConfig.from_hash({ 'port' => 1, 'log_level' => 'loud', 'database' => { 'host' => 'x', 'pool' => 1 } })
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end

begin
  AppConfig.from_hash({ 'port' => 1, 'log_level' => 'info', 'prot' => 2, 'database' => {} })
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end

begin
  AppConfig.from_hash({ 'port' => 1, 'log_level' => 'info', 'database' => { 'pool' => 1 } })
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
4567
"db.internal"
#<data DatabaseConfig host="db.internal", pool=20, timeout=5.0>
true
ArgumentError: log_level must be one of debug/info/warn/error
ArgumentError: unknown config keys: prot
ArgumentError: missing keyword: :host

Load and validate the config once at startup and pass the object around (or store it in a constant). A bad config then stops the program right away with a clear message, instead of failing an hour later in the middle of a request.

Writing config files and where to keep them

Desktop apps and CLI tools often save user preferences. Put them in the platform's config directory: $XDG_CONFIG_HOME (default ~/.config) on Linux and macOS CLI tools, %APPDATA% on Windows. Write to a temporary file first, then rename it over the old one, so a crash in the middle of a write can't leave a half-written config behind:

require 'yaml'
require 'fileutils'

def config_dir(app)
  base =
    if Gem.win_platform?
      ENV.fetch('APPDATA') { File.join(Dir.home, 'AppData', 'Roaming') }
    else
      ENV.fetch('XDG_CONFIG_HOME') { File.join(Dir.home, '.config') }
    end
  File.join(base, app)
end

def save_config(path, data)
  FileUtils.mkdir_p(File.dirname(path))
  tmp = "#{path}.tmp"
  File.write(tmp, YAML.dump(data))
  File.rename(tmp, path) # replaces the old file in one step
end

ENV['XDG_CONFIG_HOME'] = File.expand_path('xdg')
ENV['APPDATA'] = File.expand_path('xdg')
path = File.join(config_dir('bookshelf'), 'config.yml')

settings = { 'theme' => 'dark', 'recent_files' => ['a.txt', 'b.txt'], 'font_size' => 14, 'version' => '1.10' }
save_config(path, settings)
puts File.read(path)
p YAML.load_file(path) == settings
---
theme: dark
recent_files:
- a.txt
- b.txt
font_size: 14
version: '1.10'
true

YAML.dump quotes '1.10' automatically, because left unquoted it would load back as a Float. Comments in the original file are lost when you rewrite it, so files that people edit by hand and files the program writes should be separate.

Which format to use

Format Good for Watch out for
YAML hand-edited app config, Ruby ecosystem conventions implicit typing (NO, 01234, 1.10), aliases off by default
JSON machine-written files, sharing with other languages no trailing commas, comments only in lenient parsers
TOML hand-edited config with exact types needs a gem; tomlrb can't write
.env secrets and per-machine values in development flat strings only; never commit it

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents