Friday, October 07, 2005

quick and dirty xmlserializer in ruby

I've been thinking about how one might transfer objects in Ruby to XML and JSON for use in an AJAX application. There may be libraries that do it already, but I thought it might be an interesting exercise anyway.

Here's my first stab at adding XML serialization to any object. The idea is that all public attributes would be available as XML elements.

class Object
def xml
root_name = self.class.name.downcase
s = start_element(root_name)
self.instance_variables.each do |getter|
getter.gsub!(/@/, '')
# Set an id property as a class attribute
if getter == 'id'
s.gsub!(/<#{root_name}/,
"<#{root_name} id=\"#{self.send(:id).to_s}\"")
else
s << build_element(getter, self.send(getter).to_s)
end
end
s << end_element(root_name)
end
private
def build_element(name, value)
start_element(name) +
value.gsub(/ .gsub(/>/, '&gt;').gsub(/'/, '&apos;') +
end_element(name)
end
def start_element(name)
"<"+name+">"
end
def end_element(name)
""
end
end

require 'date'

class Person
attr_accessor :name, :dob, :phone, :id, :email
end

p = Person.new
p.id = 12345
p.name = "Shawn O'Malley"
p.dob = Date.new(1975, 1, 28)
p.phone = "555-555-5555"
p.email = "somalley@foobar.com"

puts p.xml

# => <person id="12345">
# <dob>1975-01-28</dob>
# <email>somalley@foobar.com</email>
# <name>Shawn O'Malley>/name><phone>555-555-5555</phone>
# </person>

0 Comments:

Post a Comment

<< Home