Sickpea

Rails App Configuration in 10 Lines

Tuesday, 30 June 2009

There are many, many, many, many Rails app config implementations out there, but I still like to use this little code snippet. Not-Invented-Here Syndrome? Perhaps. Too clever? Probably.

config/initializers/app.rb

module App
  def self.[](*args)
    args.inject(CONFIG) { |hash, arg| hash[arg] }
  end
  def self.method_missing(method, *args)
    self[method, *args]
  end
  yaml = YAML.load(ERB.new(File.read(Rails.root.join('config', 'app.yml'))).result)
  CONFIG = HashWithIndifferentAccess.new(yaml[Rails.env]).freeze
end

Just drop it into config/initializers/app.rb, and create a configuration file in config/app.yml:

config/app.yml

development:
  key: "value"
test:
  key: <%= 1 + 2 %>
production:
  key:
    subkey: "nested"

And finally the access pattern:

App.key => "value"            # in development mode
App.key => 3                  # in test mode
App.key[:subkey] => "nested"  # in production mode (also App.key['subkey'])

Archives

Previous article, on Thu, 25 Jun 2009.

Haml & Sass TextMate Bundles

Next article, on Thu, 2 Jul 2009.

Canonical URLs in Rails

Hi, I'm Adrian.

I'm a software engineer and entrepreneur. I like to build things; websites, games, robots, etc. I am currently Chief Architect at Ooga Labs / Wonderhill.

You should follow me on Twitter and subscribe to my RSS feed.

© 1988-2009 Adrian B. Danieli. Some rights reserved.