How to define custom configuration variables in Rails?

Viewed 182949

I was wondering how to add custom configuration variables to a Rails application and how to access them in the controller?

Secondly, I was planning to have S3 support for uploads in my application, if I wanted to add a yaml file with the S3 access, secret key, how do I initialize it in my Rails App and how do I access the values that I have defined in that config file.

15 Answers

Rails 6

Many outdated answers, so adding one that is specific to Rails 6.

Application specific configuration goes in initializer files. Details are here: edge guides

Example:

config/initializers/foo.rb

module MyApp
  class Application < Rails::Application
    config.test_val = 'foo'
  end
end

Alternatively:

Rails.application.config.test_val = 'foo'

This can now be accessed as:

Rails.configuration.test_val

Many more possibilities. edge guides #custom-configuration

ex, you can also set up nested namespace configurations:

config.x.payment_processing.schedule = :daily
config.x.payment_processing.retries  = 3
config.super_debugger = true

or use config_for to load entire custom config files:

config/payment.yml

production:
  environment: production
  merchant_id: production_merchant_id
  public_key:  production_public_key
  private_key: production_private_key

development:
  environment: sandbox
  merchant_id: development_merchant_id
  public_key:  development_public_key
  private_key: development_private_key

Then load it with:

config/initializers/load_payment.rb

module MyApp
  class Application < Rails::Application
    config.payment = config_for(:payment)
  end
end

Something we've starting doing at work is the ActiveSupport Ordered Hash

Which allows you to define your configuration cleanly inside the environment files e.g.

config.service = ActiveSupport::OrderedOptions.new
config.service.api_key = ENV['SERVICE_API_KEY']
config.service.shared_secret = ENV['SERVICE_SHARED_SECRET']
Related