Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 364
hackerhasid Avatar asked Sep 12 '13 15:09

hackerhasid


People also ask

Where to find Rails configuration?

You probably know that you can configure Rails in config/application. rb and config/environments/development. rb etc. But you can also leverage that for configuring your own custom settings for your application.

What is configuration in Rails?

In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The configuration file config/application. rb and environment-specific configuration files (such as config/environments/production.

What are Initializers in Rails?

An initializer is any file of ruby code stored under /config/initializers in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.

What are environment files in Rails?

Environment variables are variables located in your computer that your computer's applications use for configuration purposes. The ENV hash in your Rails application is set when your Rails application starts.


2 Answers

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.

like image 124
kik Avatar answered Sep 23 '22 21:09

kik


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"
like image 25
gaga5lala Avatar answered Sep 23 '22 21:09

gaga5lala