Ruby-on-rails – Best way to create custom config options for the Rails app

configurationenvironmentrubyruby-on-rails

I need to create one config option for my Rails application. It can be the same for all environments. I found that if I set it in environment.rb, it's available in my views, which is exactly what I want…

environment.rb

AUDIOCAST_URI_FORMAT = http://blablalba/blabbitybla/yadda

Works great.

However, I'm a little uneasy. Is this a good way to do it? Is there a way that's more hip?

Best Answer

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/yadda

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

This configuration file gets loaded from a custom initializer in config/initializers:

# Rails 2
APP_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.