Scoped Custom Configuration in Rails

Looking to add some custom configuration to your Rails app? You can utilize config_for to inject funneled configuration using different yaml files. You can use config_for in many places but for our example we'll set a new key on our configuration object and inject settings there. # config/application.rb module SomeRailsApp class Application < Rails::Application config.settings […]

Looking to add some custom configuration to your Rails app? You can utilize config_for to inject funneled configuration using different yaml files.

You can use config_for in many places but for our example we'll set a new key on our configuration object and inject settings there.

# config/application.rb

module SomeRailsApp
  class Application < Rails::Application
    config.settings = config_for(:settings)
  end
end

Now we'll have access to Rails.configuration.settings.

config_for is going to look for the root config folder for a YAML file with the same name that was provided to config_for. In our case this will be settings.yml.

# config/settings.yml

shared:
  sales: 
    email: [email protected]
    phone_number: 888-555-0987

  business_email: [email protected]
  business_phone_number: 888-555-1234

development:
  business_email: [email protected]

A few things to mention:

You can have a base set of configuration inside of the shared namespace. Everything there will be available.

Then environment specific configuration will be layered on top of shared.

This way you can have a base set of config and using environment names these settings can be overridden.

> Rails.configuration.settings
=> {sales: {email: "[email protected]", phone_number: "888-555-0987"}, business_email: "[email protected]", business_phone_number: "888-555-1234"}

Top level keys can be accessed in an object notication like so:

> Rails.configuration.settings.sales
=> {sales: {email: "[email protected]", phone_number: "888-555-0987"}

However, currently, you cannot go into the nested hash the same way.

> Rails.configuration.settings.sales.email
=> ArgumentError

Since it is just a hash you'll be able to access the nested info as such.

> Rails.configuration.settings.sales[:email]
=> "[email protected]"

To dig a little deeper, check out the documentation for more info.


Photo by @itsbrandonlopez

Source: Hashrocket