class RuboCop::Cop::Layout::Tab

This cop checks for tabs inside the source code.

@example

# bad
# This example uses a tab to indent bar.
def foo
  bar
end

# good
# This example uses spaces to indent bar.
def foo
  bar
end

Constants

MSG

Public Instance Methods

autocorrect(range) click to toggle source
# File lib/rubocop/cop/layout/tab.rb, line 48
def autocorrect(range)
  lambda do |corrector|
    spaces = ' ' * configured_indentation_width
    corrector.replace(range, range.source.gsub(/\t/, spaces))
  end
end
investigate(processed_source) click to toggle source
# File lib/rubocop/cop/layout/tab.rb, line 29
def investigate(processed_source)
  str_ranges = string_literal_ranges(processed_source.ast)

  processed_source.lines.each.with_index(1) do |line, lineno|
    match = line.match(/^([^\t]*)\t+/)
    next unless match

    prefix = match.captures[0]
    col = prefix.length
    next if in_string_literal?(str_ranges, lineno, col)

    range = source_range(processed_source.buffer,
                         lineno,
                         col...match.end(0))

    add_offense(range, location: range)
  end
end

Private Instance Methods

in_string_literal?(ranges, line, col) click to toggle source

rubocop:disable Metrics/CyclomaticComplexity

# File lib/rubocop/cop/layout/tab.rb, line 58
def in_string_literal?(ranges, line, col)
  ranges.any? do |range|
    (range.line == line && range.column <= col) ||
      (range.line < line && line < range.last_line) ||
      (range.line != line && range.last_line == line &&
       range.last_column >= col)
  end
end
string_literal_ranges(ast) click to toggle source

rubocop:enable Metrics/CyclomaticComplexity

# File lib/rubocop/cop/layout/tab.rb, line 68
def string_literal_ranges(ast)
  # which lines start inside a string literal?
  return [] if ast.nil?

  ast.each_node(:str, :dstr).each_with_object(Set.new) do |str, ranges|
    loc = str.location

    range = if str.heredoc?
              loc.heredoc_body
            else
              loc.expression
            end

    ranges << range
  end
end