Class: DeadEnd::ParseBlocksFromIndentLine

Inherits:
Object
  • Object
show all
Defined in:
lib/dead_end/parse_blocks_from_indent_line.rb

Overview

This class is responsible for generating initial code blocks that will then later be expanded.

The biggest concern when guessing code blocks, is accidentally grabbing one that contains only an “end”. In this example:

def dog
  begonn # mispelled `begin`
  puts "bark"
  end
end

The following lines would be matched (from bottom to top):

1) end

2) puts "bark"
   end

3) begonn
   puts "bark"
   end

At this point it has no where else to expand, and it will yield this inner code as a block

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code_lines:) ⇒ ParseBlocksFromIndentLine

Returns a new instance of ParseBlocksFromIndentLine.



32
33
34
# File 'lib/dead_end/parse_blocks_from_indent_line.rb', line 32

def initialize(code_lines:)
  @code_lines = code_lines
end

Instance Attribute Details

#code_linesObject (readonly)

Returns the value of attribute code_lines.



30
31
32
# File 'lib/dead_end/parse_blocks_from_indent_line.rb', line 30

def code_lines
  @code_lines
end

Instance Method Details

#each_neighbor_block(target_line) ⇒ Object

Builds blocks from bottom up



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/dead_end/parse_blocks_from_indent_line.rb', line 37

def each_neighbor_block(target_line)
  scan = AroundBlockScan.new(code_lines: code_lines, block: CodeBlock.new(lines: target_line))
    .skip(:empty?)
    .skip(:hidden?)
    .scan_while { |line| line.indent >= target_line.indent }

  neighbors = scan.code_block.lines

  block = CodeBlock.new(lines: neighbors)
  if neighbors.length <= 2 || block.valid?
    yield block
  else
    until neighbors.empty?
      lines = [neighbors.pop]
      while (block = CodeBlock.new(lines: lines)) && block.invalid? && neighbors.any?
        lines.prepend neighbors.pop
      end

      yield block if block
    end
  end
end