hackerhasid hackerhasid - 4 months ago 9
Ruby Question

Custom rails configuration section

what's the best way to create a custom configuration section for a rails app? ideally i'd like the end result to be an api call like:

Rails.configuration.foo.bar
Rails.configuration.foo.baz


e.g.

Rails.configuration.stackoverflow.api_key
Rails.configuration.stackoverflow.api_secret


and i would store the stackoverflow configuration in some .rb file (config/initializers?) and i would obviously have others that are similarly namespaced within
Rails.configuration

Answer

What you're looking for is ActiveSupport::OrderedOptions.

It is used by rails internally to set config namespace. It allows to do something like this, in config/application.rb :

module MyApp
  class Application < Rails::Application
    # ...
    config.foo = ActiveSupport::OrderedOptions.new 
    config.foo.bar = :bar
  end
end

You can then retrieve it the usual way :

Rails.configuration.foo.bar

If you want this to be environment specific, you also can use it in config/environments/*.rb rather than config/application.rb.

Comments