class RuboCop::Cop::Corrector

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.

Constants

NOOP_CONSUMER

Public Class Methods

new(source) click to toggle source

@param source [Parser::Source::Buffer, or anything

             leading to one via `(processed_source.)buffer`]

corrector = Corrector.new(cop)
Calls superclass method
# File lib/rubocop/cop/corrector.rb, line 18
def initialize(source)
  source = self.class.source_buffer(source)
  super(
    source,
    different_replacements: :raise,
    swallowed_insertions: :raise,
    crossing_deletions: :accept
  )

  # Don't print warnings to stderr if corrections conflict with each other
  diagnostics.consumer = NOOP_CONSUMER
end
source_buffer(source) click to toggle source

Duck typing for get to a ::Parser::Source::Buffer

# File lib/rubocop/cop/corrector.rb, line 68
def self.source_buffer(source)
  source = source.processed_source if source.respond_to?(:processed_source)
  source = source.buffer if source.respond_to?(:buffer)
  source = source.source_buffer if source.respond_to?(:source_buffer)

  unless source.is_a? ::Parser::Source::Buffer
    raise TypeError, 'Expected argument to lead to a Parser::Source::Buffer ' \
                     "but got #{source.inspect}"
  end

  source
end

Public Instance Methods

remove_leading(node_or_range, size) click to toggle source

Removes ‘size` characters from the beginning of the given range. If `size` is greater than the size of `range`, the removed region can overrun the end of `range`.

@param [Parser::Source::Range, RuboCop::AST::Node] range or node @param [Integer] size

# File lib/rubocop/cop/corrector.rb, line 49
def remove_leading(node_or_range, size)
  range = to_range(node_or_range)
  to_remove = range.with(end_pos: range.begin_pos + size)
  remove(to_remove)
end
remove_preceding(node_or_range, size) click to toggle source

Removes ‘size` characters prior to the source range.

@param [Parser::Source::Range, RuboCop::AST::Node] range or node @param [Integer] size

# File lib/rubocop/cop/corrector.rb, line 37
def remove_preceding(node_or_range, size)
  range = to_range(node_or_range)
  to_remove = range.with(begin_pos: range.begin_pos - size, end_pos: range.begin_pos)
  remove(to_remove)
end
remove_trailing(node_or_range, size) click to toggle source

Removes ‘size` characters from the end of the given range. If `size` is greater than the size of `range`, the removed region can overrun the beginning of `range`.

@param [Parser::Source::Range, RuboCop::AST::Node] range or node @param [Integer] size

# File lib/rubocop/cop/corrector.rb, line 61
def remove_trailing(node_or_range, size)
  range = to_range(node_or_range)
  to_remove = range.with(begin_pos: range.end_pos - size)
  remove(to_remove)
end