Class: XmlHasher::Node

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Node

Returns a new instance of Node.



5
6
7
8
9
# File 'lib/xmlhasher/node.rb', line 5

def initialize(name)
  @name = name
  @attributes = {}
  @children = []
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



3
4
5
# File 'lib/xmlhasher/node.rb', line 3

def attributes
  @attributes
end

#childrenObject

Returns the value of attribute children.



3
4
5
# File 'lib/xmlhasher/node.rb', line 3

def children
  @children
end

#nameObject

Returns the value of attribute name.



3
4
5
# File 'lib/xmlhasher/node.rb', line 3

def name
  @name
end

#textObject

Returns the value of attribute text.



3
4
5
# File 'lib/xmlhasher/node.rb', line 3

def text
  @text
end

Instance Method Details

#to_hashObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/xmlhasher/node.rb', line 11

def to_hash
  h = {}
  if text
    h[name] = text
  else
    h[name] = attributes.inject({}) { |r, (key, value)| r[key] = value if !value.nil? && !value.to_s.empty?; r }
    if children.size == 1
      child = children.first
      h[name].merge!(child.to_hash)
    else
      h[name].merge!(children.group_by { |child| child.name }.inject({}) { |r, (k, v)| v.length == 1 ? r.merge!(v.first.to_hash) : r[k] = v.map { |c| c.to_hash[c.name] }; r })
    end
  end
  h[name] = nil if h[name].empty?
  h
end