Rails: The Convenient Way to Load Custom Configuration Yaml File

kinopyo avatar


Rails.application.config_for is a convenient method to load custom yaml file from config/ folder for your current environment - development, test, and production.

Getting Started

For example, you have a payment config file like this:

  api_key: development_api_key
  base_url: http://localhost:7000
  api_key: production_api_key
  base_url: http://example.com/payment_wall

Rails.application.config_for will load the configurations for current environment. So if you're in local development mode, this will give you the

config = Rails.application.config_for(:payment)
# => { "api_key" => "development_api_key", "base_url" => "http://localhost:7000" }

# => "development_api_key"

You can also specify the environment via the env: keyword argument. Note that the value needs to be a string, not a symbol.

Rails.application.config_for(:payment, env: "production")
# => { "api_key" => "production_api_key", "base_url" => "http://example.com/payment_wall" }

config_for shortcut

If you're under Rails.application.configure context, you can omit the prefix and just call config_for.

Rails.application.configure do
  config.middleware.use ExceptionNotifier, config_for(:exception_notification)

Another common usage is to save it to the config.x namespace:

config.x.payment = config_for(:payment)

Then later, you can access it via Rails.application.config.x.payment:

# => { "api_key" => "development_api_key", "base_url" => "http://localhost:7000" }

Chain with symbolizing keys

If you want to access the configuration with symbols, you can chain it with symbolize_keys (or even deep_symbolize_keys).

config = Rails.application.config_for(:payment).symbolize_keys
# => "development_api_key"

Learn More

kinopyo avatar
Written By


Indoor enthusiast, web developer, and former hardcore RTS gamer. #parenting
Published in Rails
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.