Module: Braintree::Xml::Libxml

Defined in:
lib/braintree/xml/libxml.rb

Constant Summary collapse

LIB_XML_LIMIT =
30000000

Class Method Summary collapse

Class Method Details

._array?(node) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/braintree/xml/libxml.rb', line 64

def self._array?(node)
  node.child? && node.child.next? && node.child.name == node.child.next.name
end

._attributes_to_hash(node, hash = {}) ⇒ Object



52
53
54
55
# File 'lib/braintree/xml/libxml.rb', line 52

def self._attributes_to_hash(node, hash={})
  node.each_attr { |attr| hash[attr.name] = attr.value }
  hash
end

._build_sub_hash(hash, name) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/braintree/xml/libxml.rb', line 33

def self._build_sub_hash(hash, name)
  sub_hash = {}
  if hash[name]
    if !hash[name].kind_of? Array
      hash[name] = [hash[name]]
    end
    hash[name] << sub_hash
  else
    hash[name] = sub_hash
  end
  sub_hash
end

._children_array_to_hash(node, hash = {}) ⇒ Object



57
58
59
60
61
62
# File 'lib/braintree/xml/libxml.rb', line 57

def self._children_array_to_hash(node, hash={})
  hash[node.child.name] = node.map do |child|
    _children_to_hash(child, {})
  end
  hash
end

._children_to_hash(node, hash = {}) ⇒ Object



46
47
48
49
50
# File 'lib/braintree/xml/libxml.rb', line 46

def self._children_to_hash(node, hash={})
  node.each { |child| _node_to_hash(child, hash) }
  _attributes_to_hash(node, hash)
  hash
end

._node_to_hash(node, hash = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/braintree/xml/libxml.rb', line 17

def self._node_to_hash(node, hash = {})
  if node.text?
    raise ::LibXML::XML::Error if node.content.length >= LIB_XML_LIMIT
    hash[CONTENT_ROOT] = node.content
  else
    sub_hash = _build_sub_hash(hash, node.name)
    _attributes_to_hash(node, sub_hash)
    if _array?(node)
      _children_array_to_hash(node, sub_hash)
    else
      _children_to_hash(node, sub_hash)
    end
  end
  hash
end

.parse(xml_string) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/braintree/xml/libxml.rb', line 8

def self.parse(xml_string)
  old_keep_blanks_setting = ::LibXML::XML.default_keep_blanks
  ::LibXML::XML.default_keep_blanks = false
  root_node = LibXML::XML::Parser.string(xml_string.strip).parse.root
  _node_to_hash(root_node)
ensure
  ::LibXML::XML.default_keep_blanks = old_keep_blanks_setting
end