Class: TOML::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/toml/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(markup) ⇒ Parser

Returns a new instance of Parser.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/toml/parser.rb', line 5

def initialize(markup)
  # Make sure we have a newline on the end
  markup += "\n" unless markup.end_with?("\n")

  begin
    tree = Parslet.new.parse(markup)
  rescue Parslet::ParseFailed => failure
    puts failure.cause.ascii_tree
  end
  
  parts = Transformer.new.apply(tree)
  
  @parsed = {}
  @current = @parsed
  @current_path = ''
  
  parts.each do |part|
    if part.is_a? Key
      # Make sure the key isn't already set
      if !@current.is_a?(Hash) || @current.has_key?(part.key)
        err = "Cannot override key '#{part.key}'"
        unless @current_path.empty?
          err += " at path '#{@current_path}'"
        end
        raise err
      end
      # Set the key-value into the current hash
      @current[part.key] = part.value
    elsif part.is_a? KeyGroup
      resolve_key_group(part)
    else
      raise "Unrecognized part: #{part.inspect}"
    end
  end
end

Instance Attribute Details

#parsedObject (readonly)

Returns the value of attribute parsed.



3
4
5
# File 'lib/toml/parser.rb', line 3

def parsed
  @parsed
end

Instance Method Details

#resolve_key_group(kg) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/toml/parser.rb', line 41

def resolve_key_group(kg)
  @current = @parsed

  path = kg.keys.dup
  @current_path = path.join('.')
  
  while k = path.shift
    if @current.has_key? k
      # pass
    else
      @current[k] = {}
    end
    @current = @current[k]
  end
end