Rails: The Convenient Way to Load Custom Configuration Yaml File
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:
development:
api_key: development_api_key
base_url: http://localhost:7000
production:
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" }
config["api_key"]
# => "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)
end
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
:
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
config[:api_key]
# => "development_api_key"
Learn More
Clap to support the author, help others find it, and make your opinion count.