Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.
Ruby Inside - A Ruby Blog

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

  1. Daniel Berger says:
    November 21, 2008 at 4:14 am

    This library has clearly challenged Hpricot for coolest icon between angle brackets. I smell a showdown.

  2. Peter Cooper says:
    November 21, 2008 at 5:39 am

    lol - I'm afraid not! This one was just a quick hack-up of my own doing for the post :)

  3. John Nunemaker says:
    November 21, 2008 at 6:24 am

    Ha! 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

Twitter Mentions

AltStyle によって変換されたページ (->オリジナル) /