Class: RegexpRange

Inherits:
Object
  • Object
show all
Defined in:
lib/ndr_support/regexp_range.rb

Overview

This class provides the ability to define a range using numbers or regular expressions and when provided with an array, will return a normal ruby Range object based on the matching elements in the array. NOTE this class is has the same attributes as Range and is identical when serialized (except for the class declaration obviously), but it is NOT a substitute for Range (only a facade).

Defined Under Namespace

Classes: PatternMatchError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(range_start, range_end, exclusive = false) ⇒ RegexpRange

Returns a new instance of RegexpRange.



12
13
14
15
16
# File 'lib/ndr_support/regexp_range.rb', line 12

def initialize(range_start, range_end, exclusive = false)
  @begin = range_start
  @end = range_end
  @excl = exclusive
end

Instance Attribute Details

#beginObject (readonly)

Returns the value of attribute begin.



10
11
12
# File 'lib/ndr_support/regexp_range.rb', line 10

def begin
  @begin
end

#endObject (readonly)

Returns the value of attribute end.



10
11
12
# File 'lib/ndr_support/regexp_range.rb', line 10

def end
  @end
end

#exclObject (readonly)

Returns the value of attribute excl.



10
11
12
# File 'lib/ndr_support/regexp_range.rb', line 10

def excl
  @excl
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

‘other` is equal to self if it is a RegexpRange with the same state.



53
54
55
# File 'lib/ndr_support/regexp_range.rb', line 53

def ==(other)
  other.is_a?(RegexpRange) && other.state == state
end

#to_range(lines) ⇒ Object



18
19
20
21
22
23
24
25
26
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/ndr_support/regexp_range.rb', line 18

def to_range(lines)
  start_line_number = @begin
  if start_line_number.is_a?(Regexp)
    lines.each_with_index do |line, i|
      if line.match(start_line_number)
        start_line_number = i
        break
      end
    end

    if start_line_number.is_a?(Regexp)
      fail PatternMatchError, "begin pattern #{start_line_number.inspect} not found"
    end
  end

  end_line_number = @end
  if end_line_number.is_a?(Regexp)
    start_scan_line = start_line_number + 1
    lines[start_scan_line..-1].each_with_index do |line, i|
      # puts "##{start_scan_line + i}: #{line}"
      if line.match(end_line_number)
        end_line_number = start_scan_line + i
        break
      end
    end
    if end_line_number.is_a?(Regexp)
      fail PatternMatchError,
           "end pattern #{end_line_number.inspect} not found on or after line #{start_scan_line}"
    end
  end

  Range.new(start_line_number, end_line_number, @excl)
end