Adventures with Ruby

Writing YAML files

View Comments

A short one for today: How do I write YAML files?

Well, to get the prettiest results, I do something like this:

def write(filename, hash)
  File.open(filename, "w") do |f|
    f.write(yaml(hash))
  end
end

def yaml(hash)
  method = hash.respond_to?(:ya2yaml) ? :ya2yaml : :to_yaml
  string = hash.deep_stringify_keys.send(method)
  string.gsub("!ruby/symbol ", ":").sub("---","").split("\n").map(&:rstrip).join("\n").strip
end


I use the gem ya2yaml to create YAML, because the default Hash#to_yaml doesn’t work well with UTF-8. If you have it installed and loaded, it uses that.

Then I turn all keys into strings with the method deep_stringify_keys, so the keys don’t get formatted like the symbols they are. I remove some random junk and strip whitespace.

To add the deep_stringify_keys, open the Hash class:

class Hash
  def deep_stringify_keys
    new_hash = {}
    self.each do |key, value|
      new_hash.merge!(key.to_s => (value.is_a?(Hash) ? value.deep_stringify_keys : value)))
    end
  end
end

Here are the specs for this:

describe "Writing YAML files" do

  before :all do
    @it = YAMLWriter.new
    @hash = { :foo => { :bar => :baz } }
    @filename = File.join(File.dirname(__FILE__), "/test.yml")
  end

  it "should write a translation hash to a specified file" do
    @it.should_receive(:yaml).with(@hash).and_return("result")
    @it.write(@filename, @hash)
    File.open(@filename, "r") { |line| line.gets.should == "result" }
  end

  it "should convert a hash to a writable string" do
    @it.yaml(@hash).should == "foo:\n  bar: :baz"
  end
end

Written by Iain Hecker

May 15th, 2009 at 2:18 pm

Posted in iain.nl

  • http://www.meticulo.com Travis Bell

    Hey Iain,

    Thanks for this. Simple and easy way to write Yaml data. Cheers mate.

  • http://www.meticulo.com Travis Bell

    Hey Iain,

    Thanks for this. Simple and easy way to write Yaml data. Cheers mate.

  • Babar

    Very helpful ! Thanks.
    For more info about UTF-8 bugs see : http://www.ruby-forum.com/topic/148853#657553

  • Babar

    Very helpful ! Thanks.
    For more info about UTF-8 bugs see : http://www.ruby-forum.com/topic/148853#657553

  • http://www.the-movie-zone.net Trackback @ The Movie Zone

    Great Post!…

    [...] I found your entry interesting thus I’ve added a Trackback to it on my weblog :) [...]…

blog comments powered by Disqus
Fork me on GitHub