lib/rubocop/cop/corrector.rb in rubocop-1.41.1 vs lib/rubocop/cop/corrector.rb in rubocop-1.42.0

- old
+ new

@@ -9,10 +9,24 @@ # The nodes modified by the corrections should be part of the # AST of the source_buffer. class Corrector < ::Parser::Source::TreeRewriter NOOP_CONSUMER = ->(diagnostic) {} # noop + # Duck typing for get to a ::Parser::Source::Buffer + 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 + # @param source [Parser::Source::Buffer, or anything # leading to one via `(processed_source.)buffer`] # # corrector = Corrector.new(cop) def initialize(source) @@ -62,21 +76,19 @@ range = to_range(node_or_range) to_remove = range.with(begin_pos: range.end_pos - size) remove(to_remove) end - # Duck typing for get to a ::Parser::Source::Buffer - 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) + # Swaps sources at the given ranges. + # + # @param [Parser::Source::Range, RuboCop::AST::Node] node_or_range1 + # @param [Parser::Source::Range, RuboCop::AST::Node] node_or_range2 + def swap(node_or_range1, node_or_range2) + range1 = to_range(node_or_range1) + range2 = to_range(node_or_range2) - unless source.is_a? ::Parser::Source::Buffer - raise TypeError, 'Expected argument to lead to a Parser::Source::Buffer ' \ - "but got #{source.inspect}" - end - - source + replace(range1, range2.source) + replace(range2, range1.source) end private # :nodoc: