Class: S41C::Parser

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

Overview

:nodoc

Constant Summary collapse

BLOCK_BEGINNERS =
/\b(module|class|def|begin|do|case|if|unless|while|until)\b|{/
BLOCK_ENDERS =
/\bend\b|}/

Instance Method Summary collapse

Constructor Details

#initialize(block) ⇒ Parser

:nodoc



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/s41c/parser.rb', line 11

def initialize(block)
  sl = block.source_location
  @file, @start_line = sl.first, (sl.last)

  if @file[/\(irb\)/]
    @lines = IRB.CurrentContext.io.line(0..-1)
  else
    f = File.open(@file, 'r')
    @lines = f.lines.to_a
    f.close
    @start_line -= 1
  end # if

end

Instance Method Details

#parseObject

:nodoc



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/s41c/parser.rb', line 27

def parse
  raw = @lines[@start_line..-1]
  depth = 0
  code = []

  raw.each_with_index do |line, index|

    line.gsub!(/^\r\n/,'')
    line.gsub!(/\r\n$/,'')

    depth += line.scan(BLOCK_BEGINNERS).count
    depth -= line.scan(BLOCK_ENDERS).count

    code << line

    break if depth == 0

  end # each

  code.first.sub!(/^.*#{BLOCK_BEGINNERS}/, '')
  code.last.sub!(/#{BLOCK_ENDERS}.*$/, '')

  code.delete_if{|el| el.empty?}.join(';')
end