02
Jan
09

Making Configuration Files with YAML: Revised

So back in July 2007 I posted a blog on making configuration files with YAML, and I’ve been noticing a lot of readership on the old article. Because it seems that a lot of people are reading it I felt it was important to show how I apply this nowadays.

First I put my config.yml file within the /config/ directory within my Rails application. It looks something like this:

development: &non_production_settings
  :google_analytics:
    :api_key: "[Enter Google ID]"
  :site:
    :title: "[Title]"
    :address: "http://localhost:3000/"

test:
  <<: *non_production_settings

production:
  :google_analytics:
    :api_key: "[Enter Google ID]"
  :site:
    :title: "[Title]"
    :address: "[Address]"

Then, I create a new file called load_config.rb within the /config/initializers directory. You can name the file whatever you want – that’s just what I call it. This is where the actually YAML loading is going to happen – and this is what it looks like:

raw_config = File.read(RAILS_ROOT + "/config/config.yml")
APP_CONFIG = YAML.load(raw_config)[RAILS_ENV]

Now any time I want to all one of these variables I just call it like:

<%= APP_CONFIG[:site][:title] %>

3 Responses to “Making Configuration Files with YAML: Revised”


  1. February 2, 2009 at 4:23 pm

    Thanks for the quick yaml config how-to. I am new to RoR and this was exactly what I was looking for.

  2. February 3, 2009 at 11:00 am

    AppConfig = OpenStruct.new(YAML.load_file(“#{RAILS_ROOT}/config/app_config.yml”)[Rails.env].symbolize_keys) if require ‘ostruct’

    So you can do something like…

    AppConfig.site_title

    Not sure how it works with your nested Yaml config file though.


Leave a Reply