Class: ToonFormat::Parser

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

Overview

Parses TOON format strings into Ruby objects

Instance Method Summary collapse

Constructor Details

#initialize(input, strict: true) ⇒ Parser

Returns a new instance of Parser.



6
7
8
9
10
11
# File 'lib/toon_format/parser.rb', line 6

def initialize(input, strict: true)
  @input = input
  @lines = input.split("\n")
  @position = 0
  @strict = strict
end

Instance Method Details

#looks_like_root_object?Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
# File 'lib/toon_format/parser.rb', line 24

def looks_like_root_object?
  # If we have multiple lines and they all look like key-value pairs at the same indent level
  return false if @lines.size < 2

  @lines.all? do |line|
    line.strip.empty? || line =~ KEY_VALUE_PATTERN || line =~ KEY_ONLY_PATTERN
  end
end

#parseObject



13
14
15
16
17
18
19
20
21
22
# File 'lib/toon_format/parser.rb', line 13

def parse
  return nil if @lines.empty?

  # Check if the entire input is an object (multiple key-value pairs at root level)
  if looks_like_root_object?
    parse_root_object
  else
    parse_value
  end
end

#parse_root_objectObject



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
61
62
63
64
65
66
67
# File 'lib/toon_format/parser.rb', line 33

def parse_root_object
  result = {}

  while current_line
    line = current_line

    if line.strip.empty?
      advance
      next
    end

    if line =~ KEY_VALUE_PATTERN
      key = ::Regexp.last_match(1)
      value_str = ::Regexp.last_match(2).strip
      advance
      # Check if value is an empty array or empty object
      value = if value_str == "[]"
                []
              elsif value_str == "{}"
                {}
              else
                parse_primitive(value_str)
              end
      result[key.to_sym] = value
    elsif line =~ KEY_ONLY_PATTERN
      key = ::Regexp.last_match(1)
      advance
      result[key.to_sym] = parse_nested_value
    else
      break
    end
  end

  result
end