Class: PrintR::Parser

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Parser

Returns a new instance of Parser.



8
9
10
# File 'lib/print_r/parser.rb', line 8

def initialize(text)
  @text = text
end

Instance Attribute Details

#textObject (readonly)

Returns the value of attribute text.



6
7
8
# File 'lib/print_r/parser.rb', line 6

def text
  @text
end

Instance Method Details

#_to_key_values(lines, indent) ⇒ Object



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
# File 'lib/print_r/parser.rb', line 33

def _to_key_values(lines, indent)
  tab = "    " * indent
  h = {}
  key = nil
  val = ""
  lines.each do |line|
    md = line.match(/^#{tab}\[([^\]]+)\] => (.*)/)
    if md
      if key
        h[key] = val
        key = nil
        val = ""
      end

      key = md[1]
      val = md[2]
    else
      val += line
    end
  end

  if key
    h[key] = val
    key = nil
    val = ""
  end

  h
end

#_to_object(str, indent) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/print_r/parser.rb', line 16

def _to_object(str, indent)
  str = str.strip
  tab = "    " * indent
  if md = str.match(/^(Array|[^ ]*? Object)\n \*RECURSION\*$/m)
    obj = Recursion.new(md[1])
  elsif md = str.match(/^(?:Array|[^ ]*? Object)\n#{tab}\(\n(.*)#{tab}\)$/m)
    obj = _to_key_values(md[1].split(/(\r\n|\r|\n)/), indent+1)

    obj.each do |key, value|
      obj[key] = _to_object(value, indent+2)
    end
  else
    obj = str
  end
  obj
end

#parseObject



12
13
14
# File 'lib/print_r/parser.rb', line 12

def parse
  _to_object(text, 0)
end