Sha256: b86dc331c1d9f8df7bca3c688da64294980e082fe3994d65992324da297c0260

Contents?: true

Size: 760 Bytes

Versions: 3

Compression:

Stored size: 760 Bytes

Contents

module XmlHasher
  class Node
    attr_accessor :name, :attributes, :children, :text

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

    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
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
xmlhasher-0.0.6 lib/xmlhasher/node.rb
xmlhasher-0.0.5 lib/xmlhasher/node.rb
xmlhasher-0.0.4 lib/xmlhasher/node.rb