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
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.
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.
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.
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.
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
.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With