Rails: The Convenient Way to Load Custom Configuration Yaml File

kinopyo
Indoor enthusiast, web developer and former hardcore RTS gamer. #building-bloggie #rails #coffee #reading #writing, find out more at http://kinopyo.com
Aug 2, 2018 157 words
Edit

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:

config/payment.yml

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.

config/environments/production.rb

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/application.rb

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


Written By

kinopyo

Indoor enthusiast, web developer and former hardcore RTS gamer. #building-bloggie #rails #coffee #reading #writing, find out more at http://kinopyo.com

Enjoyed the post?

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

Comments

To leave a comment, you need to login first 😉