Class: CobraVsMongoose

Inherits:
Object
  • Object
show all
Defined in:
lib/cobravsmongoose.rb

Overview

CobraVsMongoose translates between XML documents and Ruby hashes according to the rules of the BadgerFish convention (see badgerfish.ning.com/).

Defined Under Namespace

Classes: ParseError

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.sort_keysObject

The sort_keys class attribute is useful for testing, when a predictable order is required in the generated XML. By setting CobraVsMongoose.sort_keys to true, hash-derived elements within a scope will be sorted by their element name, whilst attributes on an element will be sorted according to their name.



50
51
52
# File 'lib/cobravsmongoose.rb', line 50

def sort_keys
  @sort_keys
end

Class Method Details

.hash_to_xml(hash) ⇒ Object

Returns an XML string corresponding to the data structure of the given Hash.

E.g.

hash = { "alice" => { "$" => "bob", "@charlie" => "david" } }
CobraVsMongoose.hash_to_xml(hash)
# => "<alice charlie='david'>bob</alice>"

Note that, due to the fact that Ruby’s hashes do not preserve ordering, the order of XML elements is undefined. For a predictable order, see the sort_keys class attribute.



40
41
42
# File 'lib/cobravsmongoose.rb', line 40

def hash_to_xml(hash)
  return nested_data_to_xml(hash.keys.first, hash.values.first)
end

.xml_to_hash(xml) ⇒ Object

Returns a Hash corresponding to the data structure of the given XML string.

E.g.

xml = '<alice><bob>charlie</bob><bob>david</bob></alice>'
CobraVsMongoose.xml_to_hash(xml)
# => { "alice" => { "bob" => [{ "$" => "charlie" }, { "$" => "david" }] } }


23
24
25
26
# File 'lib/cobravsmongoose.rb', line 23

def xml_to_hash(xml)
  doc = REXML::Document.new(xml)
  return xml_node_to_hash(doc.root_node)
end