Monday, March 31, 2008

HashMagic: a utility hash extensions gem

Rubyforge: http://rubyforge.org/projects/hash-magic/
Documentation: http://hash-magic.rubyforge.org/
Install:

gem install hash_magic
HashMagic, first of all, doesn't touch Hash except for two methods. Like the FormattedString gem, it just provides a way to get a "different kind" of the original object.

HashMagic provides two special kinds of hashes: OrderedHash and SlashedHash. OrderedHash is just what it says - a hash that keeps its order. You can specify a static order, if you want. SlashedHash provides a way to expand and collapse a multi-level hash structure into a flat single-level hash, with keys joined by a slash ('/') character.

There are times when this becomes very handy -- like when I want to weed out certain keys at various levels in the hash structure, only if they're there, without having to make a very complex method to walk around the structure and not complain when things don't exist; or when I want a hash structure of ordered hashes -- yes, they play together nicely. You can order a SlashedHash, even setting the order of keys in deep levels of the structure.

This was necessary for generating xml for quickbooks qbxml -- the elements must be ordered correctly, in a multi-level structure. This was also necessary in the SimpleSync gem, for mapping attributes -- the top-level attribute 'email' in one source (quickbooks) maps to a second-level attribute on the other side, inside an association: "<emails><personal>...email...</personal></emails>". All I have to do to accomplish that is 'email' => 'emails/personal'.

You wanted to see code? Look at the HashMagic Specs!

1 comments:

Roger Pack said...

I believe facets has something similar. What would be useful would be a hash with an optimized '.each_xxx' method. That would rock :)