Module: RuboCop::Cop::AutocorrectAlignment

Overview

This module does auto-correction of nodes that should just be moved to the left or to the right, amount being determined by the instance variable @column_delta.

Constant Summary collapse

SPACE =
' '.freeze

Instance Method Summary collapse

Instance Method Details

#autocorrect(arg) ⇒ Object


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rubocop/cop/mixin/autocorrect_alignment.rb', line 51

def autocorrect(arg)
  return unless arg

  heredoc_ranges = heredoc_ranges(arg)
  expr = arg.respond_to?(:loc) ? arg.loc.expression : arg

  # We can't use the instance variable inside the lambda. That would just
  # give each lambda the same reference and they would all get the last
  # value of @column_delta. A local variable fixes the problem.
  column_delta = @column_delta

  return if block_comment_within?(expr)

  lambda do |corrector|
    each_line(expr) do |line_begin_pos|
      autocorrect_line(corrector, line_begin_pos, expr, column_delta,
                       heredoc_ranges)
    end
  end
end

#check_alignment(items, base_column = nil) ⇒ Object


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/mixin/autocorrect_alignment.rb', line 23

def check_alignment(items, base_column = nil)
  base_column ||= items.first.loc.column unless items.empty?
  prev_line = -1
  items.each do |current|
    if current.loc.line > prev_line && start_of_line?(current.loc)
      @column_delta = base_column - current.loc.column
      if @column_delta != 0
        expr = current.loc.expression
        if offenses.any? { |o| within?(expr, o.location) }
          # If this offense is within a line range that is already being
          # realigned by autocorrect, we report the offense without
          # autocorrecting it. Two rewrites in the same area by the same
          # cop can not be handled. The next iteration will find the
          # offense again and correct it.
          add_offense(nil, expr)
        else
          add_offense(current, :expression)
        end
      end
    end
    prev_line = current.loc.line
  end
end

#configured_indentation_widthObject


11
12
13
# File 'lib/rubocop/cop/mixin/autocorrect_alignment.rb', line 11

def configured_indentation_width
  config.for_cop('IndentationWidth')['Width']
end

#indentation(node) ⇒ Object


15
16
17
# File 'lib/rubocop/cop/mixin/autocorrect_alignment.rb', line 15

def indentation(node)
  offset(node) + (SPACE * configured_indentation_width)
end

#offset(node) ⇒ Object


19
20
21
# File 'lib/rubocop/cop/mixin/autocorrect_alignment.rb', line 19

def offset(node)
  SPACE * node.loc.column
end

#start_of_line?(loc) ⇒ Boolean

Returns:

  • (Boolean)

47
48
49
# File 'lib/rubocop/cop/mixin/autocorrect_alignment.rb', line 47

def start_of_line?(loc)
  loc.expression.source_line[0...loc.column].blank?
end