Configuration is where Rails apps quietly drift into inconsistency. One developer adds a constant in an initializer, another reads ENV directly in a model, and a third hard-codes a URL in a mailer. A few conventions keep settings discoverable and safe.
Where things go
config/application.rb: settings that are the same in every environment, such as time zone or autoload paths.config/environments/*.rb: settings that genuinely differ by environment, such as caching or log level.config/initializers/: one file per library or concern, named after it (sidekiq.rb,cors.rb).- Encrypted credentials or environment variables: anything secret. Never commit API keys in plain text.
Prefer custom configuration over scattered constants
Rails supports app-specific settings through config.x and config_for. Reading them through one object is easier to find and to stub in tests.
# config/payments.yml
shared:
timeout_seconds: 10
development:
base_url: http://localhost:4000
production:
base_url: https://payments.example.com
# config/application.rb
module MyApp
class Application < Rails::Application
config.payments = config_for(:payments)
end
end
# anywhere in the app
Rails.configuration.payments[:base_url]
Reading environment variables
Use ENV.fetch so a missing variable fails loudly at boot, not hours later in a background job:
config.x.support_email = ENV.fetch("SUPPORT_EMAIL")
config.x.feature_new_checkout = ENV.fetch("FEATURE_NEW_CHECKOUT", "false") == "true"
Other good habits
- Keep development, test and production as similar as possible. Every difference is a place for production-only bugs.
- Do not branch on
Rails.env.production?inside models. Express the difference as a setting instead. - Document required environment variables in the README or a sample file with placeholder values.
- Avoid putting heavy work in initializers. They run on every boot, including every test run.