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
# File 'lib/rubocop/cop/mixin/autocorrect_unless_changing_ast.rb', line 9

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

  # Make the correction only if it doesn't change the AST.
  @corrections << c if node == SourceParser.parse(new_source).ast
end

#rewrite_node(node, correction) ⇒ Object



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

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