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

Thu, 25 Jun 2009

Haml & Sass TextMate Bundles

Thu, 2 Jul 2009

Canonical URLs in Rails

Hi, I'm Adrian (@sickp).

I like to build things: websites, games, robots, and mobile apps. I'm a software tinkerer and an MIT-approved engineer (i.e. they can ask me for money.)

During the day I help build fine games at Wonderhill, and lend my expertise to other Ooga Labs companies. In my spare time, I create useful iPhone apps at Zooble with my wife, Alexandra.

You should follow me on Twitter and subscribe to this site's RSS feed.

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