Class: Ptolemy::TOML::Toml

Inherits:
Treetop:: Runtime::SyntaxNode
  • Object
show all
Defined in:
lib/ptolemy/nodes.rb

Overview

Represents the top level node of TOML AST

Instance Method Summary collapse

Instance Method Details

#to_valueHash

Evaluate the individual subtrees of the AST and then combine them to form the complete hash.

Returns:

  • (Hash)

    a (possibly nested) hash containing all key value pairs.

Raises:

  • (ParseError)

    if there are duplications in key groups or key value pairs.



20
21
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
# File 'lib/ptolemy/nodes.rb', line 20

def to_value
  result = {}
  # Keep track of location under which all the key value pairs must be
  # stored. It gets modified when a key group is encountered.
  current = result
  # Store all key groups detected so that duplicates can be discovered.
  key_group_set = Set.new

  list.elements.map do |item|
    elem = item.elem
    if elem.is_a? KeyGroup
      # Reset current to root level. Key value groups always specify
      # nesting from root
      current = result
      key_group = elem.to_value
      if key_group_set.include? key_group
        raise ParseError, "Already defined [#{key_group}] before."
      end
      key_group_set.add key_group
      # If the key group is x.y.z.w, create the whole nested structure
      # in case it doesn't exist already.
      key_group.each do |key|
        current[key] = {} if current[key].nil?
        current = current[key]
      end
    else
      key, value = elem.to_value
      # Set value in hash, if it hasn't been set already.
      if current[key].nil?
        current[key] = value
      else
        raise ParseError, "Duplicate value for key:#{key}"
      end
    end
  end
  result
end