Class: ToonToJson::Decoder

Inherits:
Object
  • Object
show all
Defined in:
lib/toon_to_json/decoder.rb

Overview

Efficiently converts TOON format directly to JSON string

Instance Method Summary collapse

Instance Method Details

#decode(str) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/toon_to_json/decoder.rb', line 6

def decode(str)
  return 'null' if str.nil? || str.empty?

  lines = str.to_s.split("\n")

  # Single-line primitive detection
  if lines.length == 1
    line = lines.first.strip

    is_structure = line.include?(':') ||
                   line.match?(/\A-\s/) ||
                   line.match?(/\A\[/)

    return primitive_to_json(line) unless is_structure
  end

  @lines = lines.map { |l| { raw: l, indent: leading_spaces(l), text: l.lstrip } }
  @i = 0
  @indent_unit = detect_indent_unit
  @output = []

  parse_block(0)
  @output.join
end