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
# 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.
  fail CorrectionNotPossible if node != SourceParser.parse(new_source).ast

  @corrections << c
end

#rewrite_node(node) ⇒ Object



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

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