#coding   #java   #ruby

I dropped YAML in favour of plain ruby for config files

January 28, 2007

write: h = { :a => 123, :b => "321", 'c' => 0.123 }

instead of

---
 :a: 123
 c: 0.123
 :b: "321"

like a lot of people i put config values in hashes and used YAML to read them from file. Take database.yml in Rails for example. YAML feels like coder nirvana when you have suffered from XML pain in Java land for many years. YAML syntax is so much nicer. But to express ruby values, plain ruby syntax for me is even more straight forward. To check syntax I always had to try and err before use with YAML.dump {:foo=>"bar"}.

I thought about just writing plain ruby and eval it. Problem is, eval avoids polluting the global namespace and the variables you set in an evaled file will not show up anywhere. Using global variables(yuck), constants, @@ variables or similar constructs would defy the purpose of getting a nice syntax for the user.

Then I got the idea of using the introspecitve powers of ruby to the retrieve the local variables which got defined on evaling a file from the binding. I wrote a function which does exactly this. From a known binding it extracts the loaded variables afterwards. The values are then injected into a hash an returned.

def load_values_from_file(filepath)
    b = binding
    v1 = eval "local_variables", b
    eval IO.read(filepath), b
    v2 = eval "local_variables", b
    (v2 - v1).inject({}) do |c, key|
        c[key.to_sym] = eval "#{key}", b
        c
    end
end

and my future config files will be plain ruby, which I know better than YAML syntax.

Technorati Tags: , ,

share this: