HappyMapper: Easy XML / Object Mapping for Rubyists
By Peter Cooper / November 20, 2008
happy-xml.jpg HappyMapper is John Nunemaker's attempt at "making XML fun again" for Rubyists by providing an object to XML mapping library with a succinct syntax. Essentially, you can use HappyMapper to rapidly turn XML into Ruby objects - even nesting them inside and referring to each other. This is powerful stuff. To install, just gem install happymapper
John's own examples are powerful demonstrations of how it works, so check them out. The first is parsing the XML returned from Twitter. The statues and associated users in that XML can be processed (with the relationship maintained) with the following code:
class User include HappyMapper element :id, Integer element :name, String element :screen_name, String element :location, String element :description, String element :profile_image_url, String element :url, String element :protected, Boolean element :followers_count, Integer end class Status include HappyMapper element :id, Integer element :text, String element :created_at, Time element :source, String element :truncated, Boolean element :in_reply_to_status_id, Integer element :in_reply_to_user_id, Integer element :favorited, Boolean has_one :user, User end statuses = Status.parse(xml_string) statuses.each do |status| puts status.user.name, status.user.screen_name, status.text, status.source, '' end
Added: Or.. how about a similar library that doesn't require naming the elements to work (but then lacks typecasting)? Check out xml-object by Jordi Bunster.
Comments
-
Daniel Berger says:
November 21, 2008 at 4:14 amThis library has clearly challenged Hpricot for coolest icon between angle brackets. I smell a showdown.
-
Peter Cooper says:
November 21, 2008 at 5:39 amlol - I'm afraid not! This one was just a quick hack-up of my own doing for the post :)
-
John Nunemaker says:
November 21, 2008 at 6:24 amHa! I actually like the icon too. If you have a non cropped version I'll use it on the post and give you props. :)
Other Posts to Enjoy
-
Ruby’s Unary Operators and How to Redefine Their Functionality
Ruby’s Unary Operators and How to Redefine Their Functionality
-
The Split is Not Enough: Unicode Whitespace Shenigans for Rubyists
The Split is Not Enough: Unicode Whitespace Shenigans for Rubyists
-
The Mega Ruby News and Release Roundup for February 2012
The Mega Ruby News and Release Roundup for February 2012
-
A Lagom Review of O’Reilly’s ‘Sinatra Up and Running’
A Lagom Review of O’Reilly’s ‘Sinatra Up and Running’