Simple application wide configuration in Rails
August 22nd, 2008
lib/app_config.rb:
class AppConfig
def self.load
config_file = File.join(RAILS_ROOT, "config", "application.yml")
if File.exists?(config_file)
config = YAML.load(File.read(config_file))[RAILS_ENV]
config.keys.each do |key|
cattr_accessor key
send("#{key}=", config[key])
end
end
end
end
config/initializers/app_config.rb:
require 'app_config'
AppConfig.load
config/application.yml:
development:
merchant_email: bob@thebuilder.com
test:
merchant_email: test@thebuilder.com
Then from anywhere in your application:
AppConfig.merchant_email -> bob@thebuilder.com
5 Responses to “Simple application wide configuration in Rails”
Sorry, comments are closed for this article.

August 22nd, 2008 at 09:16 PM
Hm, any reason to not just use constants?
August 22nd, 2008 at 09:22 PM
I always feel constants get a quite messy. This method makes defining variables much cleaner IMO.
I also like to be able to define them in yaml rather than littering the environment files.
August 22nd, 2008 at 10:39 PM
If you need access to your app config in environment.rb, you can load it in config/preinitializer.rb. The config/initializers get loaded after the environment.
However, I'm not certain the lib directory, RAILSROOT, or RAILSENV are set up at that point.
August 23rd, 2008 at 11:57 PM How about Mash (http://www.intridea.com/2008/4/13/mash-mocking-hash-for-total-poser-objects)? I then use it as so (where AppName is your application's namespace): AppName::Config = Mash.new( YAML.load_file(File.join(RAILS_ROOT, 'config/appname.yml'))[Rails.env] )
August 28th, 2008 at 06:00 PM
I stole, er borrowed, this, and modified it for Merb applications, using merb's built-in Merb::Config.
http://www.theamazingrando.com/blog/?p=34