lib/apricoteatsgorilla.rb in smacks-apricoteatsgorilla-0.2.2 vs lib/apricoteatsgorilla.rb in smacks-apricoteatsgorilla-0.2.3

- old
+ new

@@ -1,18 +1,18 @@ # -*- coding: utf-8 -*- require 'rubygems' require 'hpricot' -# Apricot eats Gorilla translates between XML documents and Ruby hashes. +# Apricot eats Gorilla translates between XML documents and Hashes. # It's based on CobraVsMongoose but uses Hpricot instead of REXML to parse # XML and it also doesn't follow the BadgerFish convention. # -# Its initial purpose was to convert SOAP response messages to Ruby hashes, +# Its initial purpose was to convert SOAP response messages to Hashes, # but it quickly evolved into a more general translation tool. class ApricotEatsGorilla - # Converts XML into a Ruby Hash. Starts parsing at root node by default. + # Converts XML into a Hash. Starts parsing at root node by default. # Call with XPath expession (Hpricot search) as second parameter to define # a custom root node. The root node itself will not be included in the Hash. # # E.g. # xml = "<dude><likes>beer</likes><hates>appletini</hates></dude>" @@ -23,11 +23,11 @@ doc = Hpricot.XML(xml) root = root_node ? doc.at(root_node) : doc.root xml_node_to_hash(root) end - # Converts a Ruby Hash to XML. + # Converts a Hash to XML. # # E.g. # hash = { "dude" => { "likes" => "beer", "hates" => "appletini" } } # ApricotEatsGorilla.hash_to_xml(hash) # # => "<dude><hates>appletini</hates><likes>beer</likes></dude>" @@ -35,11 +35,11 @@ nested_data_to_xml(hash.keys.first, hash.values.first) end private - # Converts XML nodes into a Ruby Hash. + # Converts XML into a Hash. def self.xml_node_to_hash(node) this_node = {} node.each_child do |child| if child.children.nil? @@ -62,13 +62,12 @@ end this_node end - # Converts a Ruby Hash to XML. + # Converts a Hash to XML. def self.nested_data_to_xml(name, item) - children = {} case item when String make_tag(name) { item } when Array item.map { |subitem| nested_data_to_xml(name, subitem) }.join @@ -112,5 +111,20 @@ return false if string == "false" string end end + +# Shortcut method for translating between XML documents and Hashes. +# Calls xml_to_hash in case the first parameter is of type String. +# Calls hash_to_xml in case the first parameter is of type Hash. +# Returns nil otherwise. +def ApricotEatsGorilla(source, root_node = nil) + case source + when String + ApricotEatsGorilla.xml_to_hash(source, root_node) + when Hash + ApricotEatsGorilla.hash_to_xml(source) + else + nil + end +end \ No newline at end of file