Module: Braintree::Xml::Rexml

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

Constant Summary collapse

CONTENT_KEY =
"__content__".freeze

Class Method Summary collapse

Class Method Details

._collapse(element) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/braintree/xml/rexml.rb', line 19

def self._collapse(element)
  hash = _get_attributes(element)

  if element.has_elements?
    element.each_element { |child| _merge_element!(hash, child) }
    _merge_texts!(hash, element) unless _empty_content?(element)
    hash
  else
    _merge_texts!(hash, element)
  end
end

._empty_content?(element) ⇒ Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/braintree/xml/rexml.rb', line 65

def self._empty_content?(element)
  element.texts.join.strip == ""
end

._get_attributes(element) ⇒ Object



59
60
61
62
63
# File 'lib/braintree/xml/rexml.rb', line 59

def self._get_attributes(element)
  attributes = {}
  element.attributes.each { |n,v| attributes[n] = v }
  attributes
end

._merge!(hash, key, value) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/braintree/xml/rexml.rb', line 44

def self._merge!(hash, key, value)
  if hash.has_key?(key)
    if hash[key].instance_of?(Array)
      hash[key] << value
    else
      hash[key] = [hash[key], value]
    end
  elsif value.instance_of?(Array)
    hash[key] = [value]
  else
    hash[key] = value
  end
  hash
end

._merge_element!(hash, element) ⇒ Object



15
16
17
# File 'lib/braintree/xml/rexml.rb', line 15

def self._merge_element!(hash, element)
  _merge!(hash, element.name, _collapse(element))
end

._merge_texts!(hash, element) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/braintree/xml/rexml.rb', line 31

def self._merge_texts!(hash, element)
  unless element.has_text?
    hash
  else
    # must use value to prevent double-escaping
    _merge!(
      hash,
      CONTENT_KEY,
      element.texts.map { |t| t.value }.join,
    )
  end
end

.parse(string) ⇒ Object



9
10
11
12
13
# File 'lib/braintree/xml/rexml.rb', line 9

def self.parse(string)
  require "rexml/document" unless defined?(REXML::Document)
  doc = REXML::Document.new(string)
  _merge_element!({}, doc.root)
end