xml or plist?
My new company is building an product that is both a web site and an iPhone app. Both are backed by the same web-service, which returns either xml or plists based on who’s asking.
For the web site, we return xml created using ROXML. The iPhone app does best when we send back plists, because they can be read easily with Objective C 2.0’s built-in libraries.
The following bit of code, injected into the base class of our “Service Objects” (as per Enterprise Rails), allows classes marked as with ROXML attributes to be serialized either as xml or as plists. to_xml returns the ROXML version as usual, but now xml_attributes_as_hash.to_plist returns a plist. xml_attributes_to_hash recursively turns all XML attributes into hashes (whether the attribute is another ServiceObject, an array, a hash, or a discrete value).
Of course, you need to have installed the ruby plist gem in order for “to_plist” to have any meaning.
module NewsService
class ServiceObject
include ROXML
def as_hash(val)
case val.class.to_s
when "Array"
return val.collect{|e| as_hash(e)}
when "Hash"
h = Hash.new
val.each{|k,v| h[k] = as_hash(v)}
return h
else
val.kind_of?(ServiceObject) ? as_hash(val.xml_attributes_as_hash) : val
end
end
def xml_attributes_as_hash
h = Hash.new
attrs = self.class.roxml_attrs.collect{|a| a.accessor}
for tag in attrs do
val = self.send(tag)
h[tag] = as_hash(val) if val
end
return h
end
end
end

leave a comment