From: "Jesús Gabriel y Galán" Date: 2008-11-27T18:16:01+09:00 Subject: Re: Design suggestion for translations/mappings from xml On Thu, Nov 27, 2008 at 7:00 AM, Brian Lonsdorf wrote: > Hi, i've got an xml file i'm parsing and creating objects from. > > The xml is not named, nor formatted like my objects, so i need to define > a bunch of mappings/translations. > > I'm looking for any design patterns or suggestions people might have to > elegantly solve this. > > xml example: > > BrandCode="BV" HotelCode="517" HotelName="Americas Best Value Inn and > Suites - Downtown" Overwrite="true" UnitOfMeasureCode="1"> > > > > > > > All the comforts of home conveniently... > > > object example: > > class Hotel > attr_accessor :property_name, :brand > end > > > There's a bunch of other classes and corresponding awkwardly named tags. > > It'd be killer if i could do a to_xml as well as from. But not > crucial... Here's a rough idea I though of when reading your email: module XMLMap module ClassMethods attr_reader :from_xml, :to_xml def map property, xpath_to_value (@from_xml ||= {})[xpath_to_value] = property (@to_xml ||= {})[property] = xpath_to_value end end def to_xml "implement to_xml creating all tags and attrs defined in the to_xml hash: #{self.class.to_xml.inspect}" end def from_xml xml "iterate through all xpaths from from_xml (#{self.class.from_xml.inspect}) initializing the corresponding ivars" # Alternatively you could make this a class method that returns an initialized instance end def self.included child puts "inherited" child.extend ClassMethods end end I haven't implemented the XML stuff, but it should be straightforward if you limit yourself to simple xpaths. Then you can use it like: class Test include XMLMap map :this, "/root/this/tag" map :that, "/root/that/@attr" end test = Test.new.from_xml "this_value" test.to_xml You could also implement a version of the map method that receives a hash with all the mappings or whatever. Hope this helps, Jesus.