Skip to content

Instantly share code, notes, and snippets.

@psyomn
Created October 9, 2012 14:32
Show Gist options
  • Save psyomn/3859212 to your computer and use it in GitHub Desktop.
Save psyomn/3859212 to your computer and use it in GitHub Desktop.
Making objects to XML with Rubys' reflection (still wip)
# Author::Simon Symeonidis
# This is a funky way to produce xml from a very simple object
# with very simple instance variables. I was particularly amused
# with the 'send' function since many times in OOP, we say that
# the objects are sending messages to each other; however in this
# case it's quite literal.
#
# If for some reason you want to use this dumb script to check it
# out, it's very simple. Just create a class Person with instance
# variables 'name', and 'surname' and include the module in the
# class (so inside the class, add 'include XMLer'). Once your object
# has been initialized, call to_xml, and you should have some output.
#
# Here's some sample output:
# <Person>
# <name>John</name>
# <surname>Smith</surname>
# <age>32</age>
# </Person>
#
module XMLer
XMLVersionTag = '<?xml version="1.0"?>'
def to_xml
vars = self.instance_variables
# in: [:@var1, :@var2]
# out: [:var1, :var2]
vars.each_with_index do |val,index|
vars[index] = val.to_s.gsub('@','').to_sym
end
output = XMLVersionTag
output += "<#{self.class.name}>"
vars.each do |val|
case self.send(val).class.name
when "Array"
output += process_a(val)
when "Hash"
output += process_h(val)
when "Fixnum"
output += process_i(val)
when "String"
output += "<#{val}>"
output += self.send(val)
output += "</#{val}>"
end
end
output += "</#{self.class.name}>"
end
private
def process_i(val)
process_simple(val)
end
def process_simple(val)
ret = "<#{val}>"
ret += "#{self.send(val)}"
ret += "</#{val}>"
end
def process_a(val)
ret = String.new
ret += "<#{val}>"
self.send(val).each do |el|
ret += "<#{el}/>"
end
ret += "</#{val}>"
return ret
end
def process_h(val)
ret = String.new
ret += "<#{val}>"
self.send(val).each_pair do |key,value|
ret += "<#{key}>"
case value.class.name
when "Array"
ret += process_a(value)
when "Hash"
ret += process_h(value)
when "Fixnum"
ret += process_i(value)
when "String"
ret += value
end
ret += "</#{key}>"
end
ret += "</#{val}>"
return ret
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment