Configuration files
The file
A config file, config.yml, is a hash with comments. YAML is the usual choice because a person edits it, and the shape here is one section named after the program:
app: name: demo port: 3000 debug: false
The section is not decoration: a file that also holds a database: block can be shared between programs, and each one reads its own key.
The script
Three layers in order: the defaults in code, the file over them, the environment over the file. Hash#merge is the layering, and the validation is the last line before the program starts:
require "yaml" DEFAULTS = { "name" => "app", "port" => 3000, "debug" => false }.freeze i = ARGV.index("--config") or abort("usage: ruby app.rb --config FILE") path = ARGV[i + 1] or abort("usage: ruby app.rb --config FILE") raw = YAML.safe_load_file(path) or abort("#{path}: empty config") settings = DEFAULTS.merge(raw.fetch("app") { abort("#{path}: missing app section") }) settings["port"] = Integer(ENV.fetch("APP_PORT", settings["port"])) abort("port must be positive") unless settings["port"].positive? puts "#{settings["name"]} on #{settings["port"]} (debug: #{settings["debug"]})"
safe_load_file opens and parses in one call, and the same safe rules as the YAML lesson apply. Integer() is the strict conversion: a value that is not a number raises instead of becoming zero.
Running it
ruby app.rb --config config.yml
demo on 3000 (debug: false)
The environment layer is a real override, not a second file:
APP_PORT=4000 ruby app.rb --config config.yml
demo on 4000 (debug: false)
A container sets APP_PORT and mounts the same config, and the code does not change between the laptop and the host. The precedence is documented in the README, which is the part that keeps the next reader from guessing.
Fail fast
A config error must stop the program before it opens a socket or writes a row. The abort calls above print to stderr and exit non-zero, which a supervisor and a CI job both read:
ruby app.rb --config broken.yml
broken.yml: missing app section
APP_PORT=-1 ruby app.rb --config config.yml
port must be positive
The message names the file or the setting, so the fix is a one-line edit. A program that starts with a bad config and fails on the first request wastes the time between the two.
What to watch for
Never commit the file that holds a password. Commit a
config.example.yml with empty values, read the
real one from a path in the environment, and the secret stays out of the
repository.
A key that a config does not mention should come from the defaults, but a
key that a config sets to null is a deliberate
empty value. merge keeps the null and the default
is gone; decide which one the setting means and validate it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does this program print?
require "yaml" defaults = { "name" => "app", "port" => 3000 } raw = YAML.safe_load("name: demo\nport: 4000") p defaults.merge(raw)Answer
{"name" => "demo", "port" => 4000}
merge takes the value of the file for every key it holds, so both values come from the file.
-
What does this program print?
require "yaml" raw = YAML.safe_load("app:\n port: 4000\n") p raw.fetch("app")Answer
{"port" => 4000}
fetch returns the value of the app key, which is the nested hash the document holds.
-
What does this program print?
require "yaml" raw = YAML.safe_load("app:\n port: 4000\n") begin raw.fetch("database") rescue KeyError => e puts e.class endAnswer
KeyError
fetch raises when the key is missing, which is why it can take the abort call in its block.
-
What does this program print?
require "yaml" raw = YAML.safe_load("app:\n port: null\n") defaults = { "port" => 3000, "debug" => false } p defaults.merge(raw["app"])Answer
{"port" => nil, "debug" => false}
merge replaces the default with the null the file sets, while the key the file omits keeps its default.
-
Which order does the script layer the settings in, from weakest to strongest?
Answer
Defaults in code, file, environment
The file overrides the defaults, and the environment overrides the file.
-
What does
abort("port must be positive")do?Answer
Prints the message to stderr and exits with a non-zero status
abort ends the program, which is what makes it the fail-fast call of a config check.
-
Why does the script call
Integer(value)rather thanvalue.to_i?Answer
Integer raises on a value that is not a number, while to_i returns 0
A strict conversion turns a bad setting into an error instead of a silent zero.
-
What should be committed when the real config holds a password?
Answer
A config.example.yml with empty values, while the real file is read from a path in the environment
The example documents the shape, and the secret never enters the repository.
-
What does
YAML.safe_load_file(path)do?Answer
Reads the file and parses it with the safe rules in one call
It opens the file and runs safe_load on its contents, with the same permitted classes as the YAML lesson.
-
Why does the config keep its settings under one
app:key?Answer
The same file can hold a section for another program, and each program reads its own
The section is what lets a shared config file serve several programs without their keys colliding.
Article author: Arthur Isaev