Class: RuboCop::Cop::Corrector

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/cop/corrector.rb

Overview

This class takes a source buffer and rewrite its source based on the different correction rules supplied.

Important! The nodes modified by the corrections should be part of the AST of the source_buffer.

Instance Method Summary collapse

Constructor Details

#initialize(source_buffer, corrections) ⇒ Corrector

class AndOrCorrector def initialize(node) @node = node end

def call(corrector) replacement = (@node.type == :and ? '&&' : '||') corrector.replace(@node.loc.operator, replacement) end end

corrections = [AndOrCorrector.new(node)] corrector = Corrector.new(source_buffer, corrections)

Parameters:

  • source_buffer (Parser::Source::Buffer)
  • corrections (Array(#call))

    Array of Objects that respond to #call. They will receive the corrector itself and should use its method to modify the source.



33
34
35
36
37
# File 'lib/rubocop/cop/corrector.rb', line 33

def initialize(source_buffer, corrections)
  @source_buffer = source_buffer
  @corrections = corrections
  @source_rewriter = Parser::Source::Rewriter.new(source_buffer)
end

Instance Method Details

#insert_after(range, content) ⇒ Object

Inserts new code after the given source range.

Parameters:

  • range (Parser::Source::Range)
  • content (String)


71
72
73
# File 'lib/rubocop/cop/corrector.rb', line 71

def insert_after(range, content)
  @source_rewriter.insert_after(range, content)
end

#insert_before(range, content) ⇒ Object

Inserts new code before the given source range.

Parameters:

  • range (Parser::Source::Range)
  • content (String)


63
64
65
# File 'lib/rubocop/cop/corrector.rb', line 63

def insert_before(range, content)
  @source_rewriter.insert_before(range, content)
end

#remove(range) ⇒ Object

Removes the source range.

Parameters:

  • range (Parser::Source::Range)


55
56
57
# File 'lib/rubocop/cop/corrector.rb', line 55

def remove(range)
  @source_rewriter.remove(range)
end

#replace(range, content) ⇒ Object

Replaces the code of the source range range with content.

Parameters:

  • range (Parser::Source::Range)
  • content (String)


79
80
81
# File 'lib/rubocop/cop/corrector.rb', line 79

def replace(range, content)
  @source_rewriter.replace(range, content)
end

#rewriteString

Does the actual rewrite and returns string corresponding to the rewritten source.

TODO: Handle conflict exceptions raised from the Source::Rewriter

Returns:

  • (String)


44
45
46
47
48
49
50
# File 'lib/rubocop/cop/corrector.rb', line 44

def rewrite
  @corrections.each do |correction|
    correction.call(self)
  end

  @source_rewriter.process
end