Converting a Struct’s key-value pairs into a Hash
There’s some pre-alpha software I’ve been messing with. The company has its own proprietary object store that works more or less like an extended XML store, with XQuery as the basis for the main query language. They’ve put together the beginnings of an ActiveRecord-like data access layer that allows things like:
g = Gorilla.find(:first, :conditions => 'name ftcontains "Magilla"')
So far so good. But
g.attributes
returns an error, so it’s not quite an AR-alike. The data that comes back gets returned in a much more complex object with all sorts of pointers and metadata on each top-level element. For the sake of sanity, the subset of name-value pairs most developers will be interested in, analagous to AR attributes, are accessible as an array returned by g.keys and g.values, or as pairs returned by g.each. In other words, it currently behaves more or less like a Struct — except that while g.height will return a value, it also doesn’t respond to things like g[:height], so right now it’s kinda-sorta like a half-implemented Struct, but being half-implemented maybe there’s a chance to make it act more AR-like.
One key part of AR is its elegant handling of relations. In this spirit, I set out on some initial exploration into what it would take to access a monkey’s or gorilla’s uncles via g.uncles (which right now would just return a pointer to another of these Struct-like representations of XML). I first wanted to begin getting those name-value pairs into a concise AR-like hash of their own. After some trial and error and a look through the pickaxe book, I arrived at this:
h = {}
g.each {|a,b| h.merge!({a,b}) }
and now, glory be, after this, h contains a hash of name-value pairs of the attributes. Traversing the pointers to referenced external objects to get nested hashes of Uncle-attributes inside g.uncles will be another story entirely, to say nothing of getting these things to act more like AR objects, mind you…
The URI to TrackBack this entry is: http://stinkrag.wordpress.com/2006/11/27/converting-a-structs-key-value-pairs-into-a-hash/trackback/