I've just made this "serialization" module in Ruby that takes a hash and outputs a XML string.
module Xml
extend self
def serialize(hash_obj)
hash_obj.map do |key, value|
noderize(key, value)
end
end
def noderize(key, value)
if value.class == Hash
node_value = serialize(value).join
else
node_value = value.nil? ? "" : value
end
"<#{key}>#{node_value}</#{key}>"
end
end
puts Xml.serialize({
name: "Vinicius",
username: "vnbrs",
address: {
country: {
name: "Brazil",
dial_code: 55
},
street: "R Jose Ananias Mauad",
street_number: nil,
}
})
And that outputs:
<name>Vinicius</name>
<username>vnbrs</username>
<address>
<country>
<name>Brazil</name>
<dial_code>55</dial_code>
</country>
<street>R Jose Ananias Mauad</street>
<street_number></street_number>
</address>
I've used #map
and some recursion. How could that be improved? Is it a bad implementation?