asbestossupply
asbestossupply

Reputation: 11919

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

Upvotes: 17

Views: 5082

Answers (2)

gaga5lala
gaga5lala

Reputation: 1228

In Rails 4 use custom-configuration is better.

$ Rails.configuration.x.class
# Rails::Application::Configuration::Custom < Object

Rails.application.configure do    
  # custom configuration section
  config.x.foo.bar = "foo.bar"
end

$ Rails.configuration.x.foo.bar
# "boo.bar"

Upvotes: 2

kik
kik

Reputation: 7937

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.

Upvotes: 30

Related Questions