lib/xmlhasher/node.rb in xmlhasher-1.0.5 vs lib/xmlhasher/node.rb in xmlhasher-1.0.6
- old
+ new
@@ -9,21 +9,38 @@
@attributes = {}
@children = []
end
def to_hash
- h = {}
- if text && !text.empty?
- h[name] = text
- else
- h[name] = attributes.each_with_object({}) { |(key, value), r| r[key] = value if !value.nil? && !value.to_s.empty?; }
- if children.size == 1
- h[name].merge!(children.first.to_hash)
- else
- h[name].merge!(children.group_by(&:name).each_with_object({}) { |(k, v), r| v.length == 1 ? r.merge!(v.first.to_hash) : r[k] = v.map { |c| c.to_hash[c.name] }; })
+ node_content = content
+ { name => node_content.empty? ? nil : node_content }
+ end
+
+ private
+
+ def content
+ return text if text && !text.empty?
+
+ attributes_to_hash.merge(children_to_hash)
+ end
+
+ def attributes_to_hash
+ attributes.each_with_object({}) do |(key, value), data|
+ next if value.nil? || value.to_s.empty?
+
+ data[key] = value
+ end
+ end
+
+ def children_to_hash
+ return children.first.to_hash if children.size == 1
+
+ children.group_by(&:name).each_with_object({}) do |(key, nodes), data|
+ next data.merge!(nodes.first.to_hash) if nodes.length == 1
+
+ data[key] = nodes.map do |node|
+ node.to_hash[node.name]
end
end
- h[name] = nil if h[name].empty?
- h
end
end
end