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'])