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] %>