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”

  1. Joe Says:

    Hm, any reason to not just use constants?

  2. Steve Says:

    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.

  3. Ryan Bates Says:

    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.

  4. Chris Lloyd Says:
    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] )
  5. Paul Says:

    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

Leave a Reply