Douglas F Shearer

Simple Rails Config


There are a lot of Rails config options around, but despite this, I thought I’d share mine.

My design goals for this were:

  1. Once the configuration was loaded, it would be stored in memory for the next time it was required.
  2. Nice usage syntax, like config.authentication.password rather than the oft-used config[:authentication_password].
  3. Zero dependencies outside what is already included in Rails.

config/app.yml


  # Rails Config.
  # Copyrighted(c) Douglas F Shearer 2009
  # Licensed under The MIT License.
  site:
    url: http://example.com

  authentication:
    username: bob@example.com
    password: myhackproofpassword

  flickr:
    api_key: d3c3576398a4876c920553b714bc177f
    username: flickrusername

  # Akismet.
  wordpress:
    api_key: 876c920553b7

config/initializers/config.rb


  # Rails Config Loader.
  # Copyrighted(c) Douglas F Shearer 2009
  # Licensed under The MIT License.
  module Config

    class ConfigStore

      # Takes a hash as an argument.
      # If this hash contains other hashes, these too will turned into
      # ConfigStore objects.
      def initialize(contents)
        @contents = contents

        @contents.each do |k, v|
          if v.is_a?(Hash)
            @contents[k] = self.class.new(v)
          end
        end

      end

      def method_missing(sym, *args)    
        @contents[sym.to_s] || super
      end

    end

    def config
      @@config ||= ConfigStore.new(YAML.load_file("#{RAILS_ROOT}/config/app.yml"))
    end
  end

  include Config

Usage

With both these files in place, we can now call the config from anywhere in our app:


  >> config.authentication.username
  => "bob@example.com"
  >> config.authentication.password
  => "myhackproofpassword"

I’ll probably add overrides for environment specific configuration in the future, but this covers most of my needs for now.

 

Comments


Gravatar

Ariejan de Vroom

December 01 2009 09:27

This looks very much like all the other options like SettingsLogic and Configatron.

Why did you write this? What's wrong with the other options that made you invest your time into making this?

Gravatar

Douglas F Shearer

December 01 2009 11:33

I originally wrote this sometime in 2007, when it was pretty much a roll-your own situation. I've probably spent less than an hour on it since it's inception, so no big time loss.

Yes it is pretty similar to other tools, but there's only so many reasonable ways to do this.

Just thought I'd share.

Add Your Comments


Commenting is closed for this entry.

 

You Are Here


Douglas F Shearer

This is the homepage of Douglas F Shearer, a software developer and mountainbike racer. More…

Hire Me!


I'm available for hire. Ruby, Java and PHP work, both remotely (Worldwide) and locally (Scotland). Find out more or email me.

Flickr Latest


Stay Informed


What is RSS?

Categories


  1. Bike (93)
  2. Coding (85)
  3. Other (46)

Top Tags