Class: SyntaxErrorSearch::AroundBlockScan

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_search/around_block_scan.rb

Overview

This class is useful for exploring contents before and after a block

It searches above and below the passed in block to match for whatever criteria you give it:

Example:

def dog
  puts "bark"
  puts "bark"
end

scan = AroundBlockScan.new(
  code_lines: code_lines
  block: CodeBlock.new(lines: code_lines[1])
)

scan.scan_while { true }

puts scan.before_index # => 0
puts scan.after_index # => 3

Contents can also be filtered using AroundBlockScan#skip

To grab the next surrounding indentation use AroundBlockScan#scan_adjacent_indent

Instance Method Summary collapse

Constructor Details

#initialize(code_lines:, block:) ⇒ AroundBlockScan

Returns a new instance of AroundBlockScan.



31
32
33
34
35
36
37
38
# File 'lib/syntax_search/around_block_scan.rb', line 31

def initialize(code_lines: , block:)
  @code_lines = code_lines
  @orig_before_index = block.lines.first.index
  @orig_after_index = block.lines.last.index
  @skip_array = []
  @after_array = []
  @before_array = []
end

Instance Method Details

#after_indexObject



79
80
81
# File 'lib/syntax_search/around_block_scan.rb', line 79

def after_index
  @after_index || @orig_after_index
end

#before_indexObject



75
76
77
# File 'lib/syntax_search/around_block_scan.rb', line 75

def before_index
  @before_index || @orig_before_index
end

#code_blockObject



71
72
73
# File 'lib/syntax_search/around_block_scan.rb', line 71

def code_block
  CodeBlock.new(lines: @code_lines[before_index..after_index])
end

#scan_adjacent_indentObject



60
61
62
63
64
65
66
67
68
69
# File 'lib/syntax_search/around_block_scan.rb', line 60

def scan_adjacent_indent
  before_indent = @code_lines[@orig_before_index.pred]&.indent || 0
  after_indent = @code_lines[@orig_after_index.next]&.indent || 0

  indent = [before_indent, after_indent].min
  @before_index = before_index.pred if before_indent >= indent
  @after_index = after_index.next if after_indent >= indent

  self
end

#scan_while(&block) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/syntax_search/around_block_scan.rb', line 45

def scan_while(&block)
  @before_index = before_lines.reverse_each.take_while do |line|
    next true if @skip_array.detect {|meth| line.send(meth) }

    block.call(line)
  end.reverse.first&.index

  @after_index = after_lines.take_while do |line|
    next true if @skip_array.detect {|meth| line.send(meth) }

    block.call(line)
  end.last&.index
  self
end

#skip(name) ⇒ Object



40
41
42
43
# File 'lib/syntax_search/around_block_scan.rb', line 40

def skip(name)
  @skip_array << name
  self
end