Sha256: 0a798428b8e147ab8961e32e4b18d7dc46732d886733fb9b1704c704aead7750

Contents?: true

Size: 866 Bytes

Versions: 1

Compression:

Stored size: 866 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
          if children.map(&:name).uniq.size == 1
            h[name].merge!(children.inject({}) { |r, child| (r[child.name] ||= []) << child.to_hash[child.name]; r })
          else
            h[name].merge!(children.inject({}) { |r, child| r.merge!(child.to_hash); r })
          end
        end
      end
      h[name] = nil if h[name].empty?
      h
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
xmlhasher-0.0.3 lib/xmlhasher/node.rb