class XmlHasher::Node

Attributes

attributes[RW]
children[RW]
name[RW]
text[RW]

Public Class Methods

new(name) click to toggle source
# File lib/xmlhasher/node.rb, line 5
def initialize(name)
  @name = name
  @attributes = {}
  @children = []
end

Public Instance Methods

to_hash() click to toggle source
# File lib/xmlhasher/node.rb, line 11
def to_hash
  h = {}
  if text
    if clean_attributes.empty?
      h[name] = text
    else
      h[name] = clean_attributes.merge(value: text)
    end
  else
    h[name] = clean_attributes
    if children.size == 1
      child = children.first
      h[name].merge!(child.to_hash)
    else
      h[name].merge!(children.group_by { |c| c.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

Private Instance Methods

clean_attributes() click to toggle source
# File lib/xmlhasher/node.rb, line 34
def clean_attributes
  return @clean_attributes if defined? @clean_attributes
  @clean_attributes = attributes.inject({}) { |r, (key, value)| r[key] = value if !value.nil? && !value.to_s.empty?; r }
end