This post originated from an RSS feed registered with Ruby Buzz
by Trans Onoma.
Original Post: Ruby Don't E4X
Feed Title: TRANSONOMA
Feed URL: http://feeds.feedburner.com/transonoma
Feed Description: A Light Green Agile Programming and SciTech Blog
I began work on an implementation of E4X for Ruby. I decided to tackle the problem from two ends. I began with a literal translation of the Java-esque pseudo-code given in the specification in order to obtain a fully compliant implementation. That will unfortunately take a long while to complete. But I wanted something I could use post-haste, so I also created a fresh-thought "lite" version, based on Jack Herrington's ONLamp.com article, but now much expanded. I figure in the course of time, the two versions will meet in the middle for a very Ruby-esque delivery of E4X.
Well, I like to dream. Truth is Ruby just can't provide suitable syntax without revision to core. Every alternative I've tried is worse than not using E4X in the first place. First there's the issue of name clash with built-in methods and the tag names. Does 'x.class' access element node <class>...</class> or the class Xml? I tried some variable solutions and settled on a bit of delegation. To get at these built-ins one first calls a public #self method.
x.self.class
That's acceptable. We'll manage. But then there's the worse problem of attributes access. Let's say we have this XML:
x = "<frog wartindex="10"><ft:color>green</green></frog>"
Standard E4X attribute access notation is:
x.@wartindex #=> 10
The '@' won't fly. Too bad. What alternative is there? Jack Herrington offers:
x._wartindex
Well, ick. I mean, it's livable, but underscore methods generally represent hidden methods, not something to be commonly used.
Then there's ugly problem of Namespaces. The whole call notation starts to get really shakey since you can't do:
x.ft:color
I could try to trick it, making 'ft' act like a method passing in the :color tag. That would be weak though. Parenthesis would come into play when assigning or calling additional methods againt it.
x.ft(:color)
Would that make sense? Getting real iffy now. In fact, at this point I figure we're one step away from saying screw this and using hashes for all of it.
x['@wartindex']
x['ft:color']
Look real nice, even if a little more verbose. And then we can dump the x.self.class thing too. But then, it's not so much E4X anymore. Is it?
What do you think? Is E4X important enough to change Ruby? Keep in mind that full compliance would require some changes anyway since notions like the following are part of the standard:
x.*
x.@*
x = <frog wartindex="10"><ft:color>green</green></frog>