I dropped YAML in favour of plain ruby for config files

Posted by crux on 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: , ,

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Stephan Mon, 29 Jan 2007 15:56:27 UTC

    That’s really interesting. If only we weren’t ‘hooked’ on YAML. Well – may be I’ll change that anyway. :-)

  2. Silent Tue, 30 Jan 2007 07:46:29 UTC

    I have never written anything in YAML as I am still learning the basics, I might never have to now… nice.

  3. Dieter Komendera Tue, 30 Jan 2007 22:29:20 UTC

    Very interesting… It’s a matter of your flavor if you prefer YAML or Ruby, but it’s always good to have a choice.

Comments