Rails: Using custom config files with the config_for method

Updated . Posted . Visible to the public. Repeats.

You can use the config.x Show archive.org snapshot configuration in combination with config_for to configure global settings for your Rails 4.2+ application.

Example

In your config/application.rb assign the settings from e.g. config/settings.yml as follows:

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

The config/settings.yml might look as follows:

shared:
  email: info@example.com
  google_analytics:
    container: UA-123456-12

production:
  email: production@example.com    

Keys under the shared namespace are shared between all environments. Environment specific configs will override those shared values. Afterwards you can access these settings with e.g. Rails.application.config.x.settings.google_analytics.fetch(:container) or Rails.configuration.x.settings.google_analytics.fetch(:container) in your application.

Additional notes

  • The config.x is a dedicated namespace and helps you to avoid collisions with config options related to Rails itself.

  • The config.x returns an OrderedOptions Show archive.org snapshot object for the first two levels, but not deeper.

  • This approach might be preferred over global constants like config/constants/settings.rb:

    • It can be used in the Rails Configuration itself and all initializers.
    • It allows to write environment dependent settings.
  • Undefined keys return nil if not present e.g. Rails.application.config.foobar => nil.

  • If you need to ensure the value of key is not blank, use the bang method e.g. Rails.application.config.foobar!. This is recommended for a value that must exist in any case (no blank value).

  • For many other cases it more useful to use #fetch instead of the attribute accessors to ensure you have no typos in your config e.g. Rails.application.config.fetch(:foobar). You might also want to chain the method calls for nested configs e.g. Rails.application.config.fetch(:foobar).fetch(:bar). This approach allows you to have '', true, false and nil in your config.

Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2024-01-09 10:07)