If you have to deal with multiple configuration values for different environments, this easy and very simple trick will let you put all these values to an external YML file and have a convenient global hash to access the values. Another benefit of putting config values in a YML file is that you can re-factor shared values into a default block, and override values in environment-specific blocks. You can keep your code DRY, now keep your config DRY as well, instead of littering your different environment config files.
In your environment.rb, add this one line between the Rails::Initializer.run do … end block
Rails::Initializer.run do |config|
# ... other config code
SITE_CONFIG = YAML.load_file( "#{RAILS_ROOT}/config/site_config.yml" )[ ENV['RAILS_ENV'] || RAILS_ENV ]
end
Create a new “site_config.yml” file the /config folder using the following skeleton:
# config/site_config.yml # the shared configurations. Override values here in each individual environment. defaults: &defaults twitter_username: your_username twitter_password: your_password # Blog blog_url: http://alexle.net blog_feed: http://alexle.net/feed/ blog_email: development: <<: *defaults # override twitter_username: dev_username twitter_password: dev_password slicehost: <<: *defaults test: <<: *defaults staging: <<: *defaults production: <<: *defaults
Restart your web server so that the environment.rb file is picked up. Now within your code, you can access the values using
logger.debug SITE_CONFIG["twitter_username"]
The only gotcha of this method is that we cannot override nested configuration blocks due to the way YML files are interpreted.
# this sample won't work
defaults: &defaults
twitter:
username:
password:
development:
<<: *defaults
# this override doesn't work since it replaces the twitter hash in the defaults block with a new
# hash containing only the "username" key (The "password" key-value is gone!)
twitter:
username: dev_username
cheers!