Module: Transformator::FormatConverter::HashFromDocument

Included in:
Transformator::FormatConverter
Defined in:
lib/transformator/format_converter/hash_from_document.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.process_node(node, hash) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/transformator/format_converter/hash_from_document.rb', line 22

def self.process_node(node, hash)
  value =
  if (child_nodes = node.nodes).all? { |child_node| child_node.is_a?(String) }
    case node[:type]
    when "integer" then child_nodes.join.to_i
    when "float" then child_nodes.join.to_f
    when "boolean" then child_nodes.join.downcase == "true"
    else node[:nil] == "true" ? nil : child_nodes.join
    end
  else
    if node[:type] == "array"
      node.locate(node.value)
      .map do |child_node|
        if (arr_element = process_node(child_node, {})).is_a?(Hash) && arr_element.keys == [node.value]
          arr_element.values.first
        else
          arr_element
        end
      end
    else
      {}.tap do |child_nodes_hash|
        child_nodes.each do |child_node|
          process_node(child_node, child_nodes_hash)
        end
      end
    end
  end

  hash[node.value] =
  if hash[node.value].nil?
    value
  elsif hash[node.value].is_a?(Array)
    hash[node.value] << value
  else
    [hash[node.value], value]
  end

  hash
end

Instance Method Details

#hash_from_document(document) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/transformator/format_converter/hash_from_document.rb', line 4

def hash_from_document(document)
  document =
  if document.root.value == "hash"
    document
  else
    hash_container_document = Ox::Document.new
    hash_container_document << (hash_root_element = Ox::Element.new("hash"))
    document.nodes.each do |node|
      hash_root_element << node
    end

    hash_container_document
  end

  hash = Transformator::FormatConverter::HashFromDocument.process_node(document.root, {})
  hash["hash"].nil? ? hash : hash["hash"]
end