Class: RuboCop::RSpec::ExpectOffense::AnnotatedSource

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/rspec/expect_offense.rb

Overview

Parsed representation of code annotated with the `^^^ Message` style

Constant Summary collapse

ANNOTATION_PATTERN =
/\A\s*\^+ /.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lines, annotations) ⇒ AnnotatedSource

Note:

annotations are sorted so that reconstructing the annotation text via #to_s is deterministic

Returns a new instance of AnnotatedSource


172
173
174
175
# File 'lib/rubocop/rspec/expect_offense.rb', line 172

def initialize(lines, annotations)
  @lines       = lines.freeze
  @annotations = annotations.sort.freeze
end

Class Method Details

.parse(annotated_source) ⇒ AnnotatedSource

Separates annotation lines from source lines. Tracks the real source line number that each annotation corresponds to.


151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/rubocop/rspec/expect_offense.rb', line 151

def self.parse(annotated_source)
  source      = []
  annotations = []

  annotated_source.each_line do |source_line|
    if source_line =~ ANNOTATION_PATTERN
      annotations << [source.size, source_line]
    else
      source << source_line
    end
  end

  new(source, annotations)
end

Instance Method Details

#plain_sourceString

Return the plain source code without annotations


213
214
215
# File 'lib/rubocop/rspec/expect_offense.rb', line 213

def plain_source
  lines.join
end

#to_sString

Construct annotated source string (like what we parse)

Reconstruct a deterministic annotated source string. This is useful for eliminating semantically irrelevant annotation ordering differences.

Examples:

standardization


source1 = AnnotatedSource.parse("line1\n^ Annotation 1\n^^ Annotation 2\n")

source2 = AnnotatedSource.parse("line1\n^^ Annotation 2\n^ Annotation 1\n")

source1.to_s == source2.to_s # => true

200
201
202
203
204
205
206
207
208
# File 'lib/rubocop/rspec/expect_offense.rb', line 200

def to_s
  reconstructed = lines.dup

  annotations.reverse_each do |line_number, annotation|
    reconstructed.insert(line_number, annotation)
  end

  reconstructed.join
end

#with_offense_annotations(offenses) ⇒ self

Annotate the source code with the RuboCop offenses provided


222
223
224
225
226
227
228
229
230
231
232
# File 'lib/rubocop/rspec/expect_offense.rb', line 222

def with_offense_annotations(offenses)
  offense_annotations =
    offenses.map do |offense|
      indent     = ' ' * offense.column
      carets     = '^' * offense.column_length

      [offense.line, "#{indent}#{carets} #{offense.message}\n"]
    end

  self.class.new(lines, offense_annotations)
end