Best way to create custom config options for my Rails app?
For general application configuration that doesn't need to be stored in a database table, I like to create a config.yml
file within the config directory. For your example, it might look like this:
defaults: &defaults audiocast_uri_format: http://blablalba/blabbitybla/yaddadevelopment: <<: *defaultstest: <<: *defaultsproduction: <<: *defaults
This configuration file gets loaded from a custom initializer in config/initializers:
# Rails 2APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]# Rails 3+APP_CONFIG = YAML.load_file(Rails.root.join('config/config.yml'))[Rails.env]
If you're using Rails 3, ensure you don't accidentally add a leading slash to your relative config path.
You can then retrieve the value using:
uri_format = APP_CONFIG['audiocast_uri_format']
See this Railscast for full details.
Rails 3 version of initialiser code is as follows (RAILS_ROOT & RAILS_ENV are deprecated)
APP_CONFIG = YAML.load_file(Rails.root.join('config', 'config.yml'))[Rails.env]
Also, Ruby 1.9.3 uses Psych which makes merge keys case sensitive so you'll need to change your config file to take that into account, e.g.
defaults: &DEFAULTS audiocast_uri_format: http://blablalba/blabbitybla/yaddadevelopment: <<: *DEFAULTStest: <<: *DEFAULTSproduction: <<: *DEFAULTS
Rails >= 4.2
Just create a YAML
file into config/
directory, for example: config/neo4j.yml
.
Content of neo4j.yml
can be somthing like below(For simplicity, I used default for all environments):
default: &default host: localhost port: 7474 username: neo4j password: rootdevelopment: <<: *defaulttest: <<: *defaultproduction: <<: *default
in config/application.rb
:
module MyApp class Application < Rails::Application config.neo4j = config_for(:neo4j) endend
Now, your custom config is accessible like below:
Rails.configuration.neo4j['host'] #=>localhostRails.configuration.neo4j['port'] #=>7474
More info
Rails official API document describes config_for
method as:
Convenience for loading config/foo.yml for the current Rails env.
If you do not want to use a yaml
file
As Rails official guide says:
You can configure your own code through the Rails configuration object with custom configuration under the
config.x
property.
Example
config.x.payment_processing.schedule = :dailyconfig.x.payment_processing.retries = 3config.x.super_debugger = true
These configuration points are then available through the configuration object:
Rails.configuration.x.payment_processing.schedule # => :dailyRails.configuration.x.payment_processing.retries # => 3Rails.configuration.x.super_debugger # => trueRails.configuration.x.super_debugger.not_set # => nil
Official Reference for config_for
method | Official Rails Guide