Module: RuboCop::Cop::AutocorrectUnlessChangingAST

Included in:
Style::AndOr, Style::Blocks, Style::Not
Defined in:
lib/rubocop/cop/mixin/autocorrect_unless_changing_ast.rb

Overview

This module does auto-correction of nodes that could become grammatically different after the correction. If the code change would alter the abstract syntax tree, it is not done.

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/rubocop/cop/mixin/autocorrect_unless_changing_ast.rb', line 9

def autocorrect(node)
  c = correction(node)
  new_source = rewrite_node(node)

  # Make the correction only if it doesn't change the AST.
  if node != ProcessedSource.new(new_source).ast
    fail CorrectionNotPossible
  end

  @corrections << c
end

#rewrite_node(node) ⇒ Object



21
22
23
24
25
# File 'lib/rubocop/cop/mixin/autocorrect_unless_changing_ast.rb', line 21

def rewrite_node(node)
  processed_source = ProcessedSource.new(node.loc.expression.source)
  c = correction(processed_source.ast)
  Corrector.new(processed_source.buffer, [c]).rewrite
end