Keep Configuration out of Your Rails Apps with YAML

Wednesday, August 5th, 2009

Do you have usernames, passwords or other configuration values mixed with code in your Ruby on Rails application? A YAML file will help keep these values out of your code. For example, I use YAML:load to load and parse my twitter.yml file stored in the config folder. The twitter.yml file contains the credentials for the Twitter account I am accessing.

/app/controllers/twitter_controller.rb

config = YAML::load( File.read( File.join(Rails.root, 'config', 'twitter.yml') ) )

/config/twitter.yml

email: email@domain.com
password: twitter

After the YAML file is loaded, the values in twitter.yml are saved to my local variable, config. I can use them in my Ruby file such as the following example with a Twitter class I have created.

/app/controller/twitter_controller.rb

config = YAML::load( File.read( File.join(Rails.root, 'config', 'twitter.yml') ) )
twitter = Twitter.new(config['email'], config['password'])

In the future, I’ll explain how to load and cache Twitter updates to the database and how to use different config files for different environments. These scripts were written for Ruby 1.8 and Rails 2.3.2.

Leave a Response

You must be logged in to post a comment.