YAML as a config format

 So, I like YAML as a format for configuration data.
It’s readable and easy to edit for a mere human.

---
:foo: :bar
:hash:
  :thingy: widget
:key: value

The top-level object is a Hash; that way a configuration can easily be treated as key/value pairs. And it’s just as easy to load:

require 'yaml'config = YAML.load( File.open( 'the_config_file_name.yaml') )

It’s the usage of Hashes I don’t like so much: Having to type

do_something_using config[ :foo ]

This is already more typing than I like. And there’s more that bothers me. It just doesn’t look like using a config, and it certainly doesn’t look particularly oo…
What I’d like to type is this:

do_something_using config.foo

Now, you could read the YAML file and then do some metaprogramming to generate accossors on the fly. I could. And I did. But in the end I didn’t like what I wrote. After rethinking it all on a long train journey, I came up with this short and easily understandable few lines of code:

class Hash
   def method_missing( name, *args )
       if has_key? name
           self name ]
       elsif has_key? name.to_s
           self name.to_s ]
       else
          super
       end
   end
end

That way, you better not have keys which contain spaces or other characters not allowed in Ruby method names, but a short and easy way to access configuration data.

Advertisements

2 thoughts on “YAML as a config format

  1. I know, I’m a bit late…

    OpenStruct does what you want and it is initializable with a Hash. So you would basically just write:

    require 'yaml'
    require 'ostruct'
    config = OpenStruct.new(YAML.load(File.open('the_config_file_name.yaml')))

  2. You’re absolutely right and there’s obviously more than one way to do it.
    For example, there’s this article on ‘Err the Blog’.

    Anyway, I looked for something which allows reading a YAML file into something that could respond the the hash keys as if they were methods, but which doesn’t allow assigning values to new keys. The reason for this (as far as I remember) was, that typically configuration files are only read by the application that uses them.

    Even though this still holds true for a test environment (which is my context of using configuration data), it’s less valid for, say, a word processor or web browser. You wouldn’t like to open a YAML file in an editor to change the default tab behaviour of your favourite browser, would you?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s