Skip to content

Instantly share code, notes, and snippets.

@JesseHerrick
Created July 24, 2015 15:00
Show Gist options
  • Save JesseHerrick/c1d9655e6cebfbeb3b9f to your computer and use it in GitHub Desktop.
Save JesseHerrick/c1d9655e6cebfbeb3b9f to your computer and use it in GitHub Desktop.
Because no one should have to figure out how to do this again. A recursive way to convert a Ruby hash into raw xml.
# this method is used to create a full XML structure for the Freshbooks API
# don't expect it to work for anything else
def to_xml(data_hash)
req_method = data_hash.delete(:method)
'<?xml version="1.0" encoding="utf-8"?>' +
"<request method=\"#{req_method}\">" +
hash_to_raw_xml(data_hash) +
'</request>'
end
# converts a hash to raw XML
def hash_to_raw_xml(object, built = '')
case object
when Hash
case
when object.count > 1
object.each { |h| built += "<#{h.first.to_s}>#{hash_to_raw_xml(h.last)}</#{h.first.to_s}>" }
when object.count == 1
object.each { |h| built += "<#{h.first.to_s}>#{hash_to_raw_xml(h.last, built)}</#{h.first.to_s}>" }
end
when String
built += object
end
built
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment