Heading image for post: Scoped Custom Configuration in Rails

Ruby

Scoped Custom Configuration in Rails

Profile picture of Matt Polito

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: sales@example.com
    phone_number: 888-555-0987

  business_email: business@example.com
  business_phone_number: 888-555-1234

development:
  business_email: major_business@example.com

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: "sales@example.com", phone_number: "888-555-0987"}, business_email: "business@example.com", business_phone_number: "888-555-1234"}

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

> Rails.configuration.settings.sales
=> {sales: {email: "sales@example.com", 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]
=> "sales@example.com"

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


Photo by @itsbrandonlopez

More posts about Ruby rails

  • Adobe logo
  • Barnes and noble logo
  • Aetna logo
  • Vanderbilt university logo
  • Ericsson logo

We're proud to have launched hundreds of products for clients such as LensRentals.com, Engine Yard, Verisign, ParkWhiz, and Regions Bank, to name a few.

Let's talk about your project