Wednesday, August 26, 2009

yaml.rb

I spent some time last week working on a problem that had me digging into Ruby's Standard Library implementation of yaml. I thought I'd take a few minutes to share some thoughts

Deep Serialization

To me, this was the reason I was using yaml over json or xml in the first place. I was in Rails and was eager loading an ActiveRecord object. I'd expect the #to_xml or #to_json methods to create a deeply nested structured document including all the associations I eager loading. But that's not the case.

However I was pleasantly surprised to find that #to_yaml did in fact do this. (It's not exactly apples to apples, #to_yaml is part of the Ruby Standard Library and #to_json and #to_xml are implemented in Rails.)

This was the home run feature for me so yaml and I started to get close.

Smart Class Transformations

Let's say our test.yml file looks like this:

--- !ruby/object:Family
kids:
!ruby/object:Kid
name: Beef
- !ruby/object:Kid
name: OshGosh
name: McSpadden

If you fire up irb and do:

require 'yaml'
YAML.load(File.read(test.yml))

You'll get something like:

#<YAML::Object:0x580408 @ivars={"name"=<"McSpadden", "kids"=>[#<YAML::Object:0x580660 @ivars={"name"=>"OshGosh"}, @class="Kid">]}, @class="Family">

So we've got some kind of yaml object with @ivars that looks to hold all the good stuff. Wouldn't it be nice if it just gave us Family and Kid objects! Yes it would be, but right now, since we're just irb-ing, YAML has no idea what a Family or Kid object looks like. Let's try this:


class Family; attr_accessor :name; end
class Kid; attr_accessor :name; end

YAML.load(File.read(test.yml))
#=> #<Family:0x576624 @name="McSpadden", @kids=[#<Kid:0x5768a4 @name="OshGosh">]>

That's what I'm talking about!

yaml-lab

I've found that when experimenting with new libraries it helps me to write a quick spec suite to test assumptions and understanding. In this vein, I've created a yaml-lab project on github with some of my experimentation. Feel free to clone it, fork it, whatever it. Here's the link yaml-lab on github.

That's all for now.

No comments:

Post a Comment