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:
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.