views:

53

answers:

4

Hi,

I have a hash like,

object = { :type => 'book', :name => 'RoR', :price => 33 }

OR

object = { :type => 'wig', :name => 'Elvis-Style', :price => 40, :color => 'black' }

The problem is that keys in above hash may be different all the time or even increase and decrease depending upon the object type.

What I want to do generate XML for above hashes using Xml::Builder. The XML tags are decided by the keys in the hash and text inside a tag is value corresponding that key.

I can use eval to do this like below. However, I think there must be a better way to do it.

object.each do |key, text|
  eval("xml.#{key.to_s} do
          #{text}
        end
      ")
end
A: 
   out << "<#{key}>#{html_escape(value)}</#{key}>"
glebm
+2  A: 
@object.each do |k, v|
  xml.tag!(k.to_s, v)
end
Jimmy Cuadra
That was great. However it did not work properly. This one did work though. http://pastie.org/851304
Waseem
A: 

This one worked.

@object.each do |k, v|
  xml.tag!(k.to_s, v)
end
Waseem
+1  A: 

Rails supports to_xml on Hash classes.

hash = { :type => 'book', :name => 'RoR', :price => 33 }
hash.to_xml
# Returns
# <?xml version=\"1.0\" encoding=\"UTF-8\"?>
# <hash>
#   <type>book</type>
#   <name>RoR</name>
#   <price type=\"integer\">33</price>
# </hash>

If you want to skip the types then:

hash.to_xml(:skip_types => true)

If you want to give a different root then:

hash.to_xml(:root => 'options')
KandadaBoggu