Environment Overrides¶
Override any configuration value using environment variables.
Basic Syntax¶
Environment variables use the pattern:
For your config:
class MyApp::Config < MywayConfig::Base
config_name :myapp
env_prefix :myapp # This sets the prefix
# ...
end
Override values:
Nested Values¶
Use double underscore (__) for nested keys:
# Override database.host
MYAPP_DATABASE__HOST=custom-db.local
# Override database.port
MYAPP_DATABASE__PORT=5433
# Override api.headers.content_type
MYAPP_API__HEADERS__CONTENT_TYPE=text/plain
Priority Order¶
Environment variables have high priority. Values are loaded in order:
- Bundled defaults (lowest)
- Environment-specific overrides from YAML
- XDG user config
- Project config
- Environment variables (high priority)
- Constructor overrides (highest)
Type Coercion¶
Values are automatically coerced based on the default type:
defaults:
port: 5432 # Integer
debug: false # Boolean
timeout: 30.5 # Float
log_level: :info # Symbol
MYAPP_PORT=9999 # Becomes Integer 9999
MYAPP_DEBUG=true # Becomes Boolean true
MYAPP_TIMEOUT=60.0 # Becomes Float 60.0
MYAPP_LOG_LEVEL=warn # Becomes Symbol :warn
Examples¶
Running with Overrides¶
# Development with custom database
MYAPP_DATABASE__HOST=localhost MYAPP_DATABASE__PORT=5433 ruby app.rb
# Production-like settings locally
RACK_ENV=production MYAPP_DATABASE__HOST=prod-db.local ruby app.rb
In Docker¶
In docker-compose¶
services:
app:
environment:
- RACK_ENV=production
- MYAPP_DATABASE__HOST=db
- MYAPP_DATABASE__PORT=5432
In Heroku¶
Checking Values¶
Verify environment variable overrides are working:
config = MyApp::Config.new
puts "Database host: #{config.database.host}"
puts "From env: #{ENV['MYAPP_DATABASE__HOST']}"
Debugging¶
If values aren't being picked up, check:
- Prefix matches -
env_prefixin your class must match - Double underscore - Nested keys need
__ - Case sensitivity - Environment variables are uppercase
- Load order - Config class must be loaded after env vars are set
Next Steps¶
- Custom File Loading - Load from non-standard locations
- Hash-like Behavior - ConfigSection features