Introduction to GrumpyMapper Build Status

GrumpyMapper is a simple alternative to the excellent HappyMapper gem. Unlike HappyMapper it only works one way - parsing XML into a Ruby object. It is also more difficult to use as it assumes some knowledge of XPath. I did create the gem for myself but as a reference for my future self and perhaps a lost visitor to this repository below is some documentation.

Using GrumpyMapper

GrumpyMapper is a module which you include in your classes. Once included, it gives access to three class macros ("tag", "has_one" and "has_many") as well as one class method ("parse"). Here is how you'd use it:

class Venue
  include GrumpyMapper
  tag "//venue"
  has_one :name,         ".//name/text()",  String
  has_one :latitude,     ".//lat/text()",   Float
  has_one :longitude,    ".//long/text()",  Float
end


class Event
  include GrumpyMapper
  tag "//event"
  has_one :name,        ".//title/text()",          String
  has_one :cancelled,    ".//cancelled/text()",     Boolean
  has_one :venue,       ".//venue",                 Venue
  has_one :start_date,  ".//startDate/text()",      DateTime
  has_many :artists,    ".//artists/artist/text()", String
end

events = Event::parse(some_xml_content) # ... events is an Array of Event objects

For a piece of XML this is supposed to parse, please see fixtures/lastfm.xml or the unit test for this library. In any case, the "tag" class macro defines what is the parent tag for your mapped object. Both attributes and children are then defined using XPath expressions in "has_one" and "has_many" class macros. Each of these macros takes at least three arguments - the attribute to map to the value to, the XPath expression (can be an attribute as well as an element) to search by and the expected class of the element found. A number of simple classes is supported - that is String, Integer, Float, Date and DateTime. A Boolean class is defined inside the GrumpyMapper as Ruby does not have one built-in. If you specify any other class, it should be one that responds to the "parse" class method - preferably one that also includes the GrumpyMapper module. One slight difference between "has_one" and "has_many" class macros is that the first allows you to specify a default value as the fourth argument. It will be used when the XPath expression finds no matches. Some expected classes like String, Integer and Float have a default default - "", 0 and 0.0 respectively. For others it is a Ruby native nil value. The "has_many" class macro always has an empty Array as it's default.

Parting words

For more inspiration on how to use the library use the unit test, source code and make sure to have your favorite XPath tutorial close at hand. Enjoy!