There are a lot of Rails config options around, but despite this, I thought I’d share mine.

My design goals for this were:

  1. Once the configuration was loaded, it would be stored in memory for the next time it was required.
  2. Nice usage syntax, like config.authentication.password rather than the oft-used config[:authentication_password].
  3. Zero dependencies outside what is already included in Rails.

config/app.yml

# Rails Config.
# Copyrighted(c) Douglas F Shearer 2009
# Licensed under The MIT License.
site:
  url: http://example.com

authentication:
  username: bob@example.com
  password: myhackproofpassword

flickr:
  api_key: d3c3576398a4876c920553b714bc177f
  username: flickrusername

# Akismet.
wordpress:
  api_key: 876c920553b7

config/initializers/config.rb

# Rails Config Loader.
# Copyrighted(c) Douglas F Shearer 2009
# Licensed under The MIT License.
module Config

  class ConfigStore

    # Takes a hash as an argument.
    # If this hash contains other hashes, these too will turned into
    # ConfigStore objects.
    def initialize(contents)
      @contents = contents

      @contents.each do |k, v|
        if v.is_a?(Hash)
          @contents[k] = self.class.new(v)
        end
      end

    end

    def method_missing(sym, *args)    
      @contents[sym.to_s] || super
    end

  end

  def config
    @@config ||= ConfigStore.new(YAML.load_file("#{RAILS_ROOT}/config/app.yml"))
  end
end

include Config

Usage

With both these files in place, we can now call the config from anywhere in our app:

>> config.authentication.username
=> "bob@example.com"
>> config.authentication.password
=> "myhackproofpassword"

I’ll probably add overrides for environment specific configuration in the future, but this covers most of my needs for now.