Class: Nokogiri::XML::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/isodoc/generic/metadata.rb

Constant Summary collapse

TYPENAMES =
{ 1 => "element", 2 => "attribute", 3 => "text",
4 => "cdata", 8 => "comment" }.freeze

Instance Method Summary collapse

Instance Method Details

#to_hashObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/isodoc/generic/metadata.rb', line 9

def to_hash
  { kind: TYPENAMES[node_type], name: name }.tap do |h|
    h[:text] = text&.strip
    a = attribute_nodes.map(&:to_hash)
    if element? && !a.empty?
      h[:attr] = a.inject({}) do |m, v|
        m[v[:name]] = v[:text]
        m
      end
    end
    c = children.map(&:to_hash)
    if element? && !(c&.size == 1 && c[0][:kind] == "text")
      h.merge! kids: c.delete_if { |n| n[:kind] == "text" && n[:text].empty? }
    end
  end
end