Class: XmlHasher::Node
- Inherits:
-
Object
- Object
- XmlHasher::Node
- Defined in:
- lib/xmlhasher/node.rb
Instance Attribute Summary collapse
-
#attributes ⇒ Object
Returns the value of attribute attributes.
-
#children ⇒ Object
Returns the value of attribute children.
-
#name ⇒ Object
Returns the value of attribute name.
-
#text ⇒ Object
Returns the value of attribute text.
Instance Method Summary collapse
-
#initialize(name) ⇒ Node
constructor
A new instance of Node.
- #to_hash ⇒ Object
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
#attributes ⇒ Object
Returns the value of attribute attributes.
3 4 5 |
# File 'lib/xmlhasher/node.rb', line 3 def attributes @attributes end |
#children ⇒ Object
Returns the value of attribute children.
3 4 5 |
# File 'lib/xmlhasher/node.rb', line 3 def children @children end |
#name ⇒ Object
Returns the value of attribute name.
3 4 5 |
# File 'lib/xmlhasher/node.rb', line 3 def name @name end |
#text ⇒ Object
Returns the value of attribute text.
3 4 5 |
# File 'lib/xmlhasher/node.rb', line 3 def text @text end |
Instance Method Details
#to_hash ⇒ Object
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 && !text.empty? 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 |