class RuboCop::Cop::Layout::TrailingWhitespace

This cop looks for trailing whitespace in the source code.

@example

# The line in this example contains spaces after the 0.
# bad
x = 0

# The line in this example ends directly after the 0.
# good
x = 0

Constants

MSG

Public Instance Methods

autocorrect(range) click to toggle source
# File lib/rubocop/cop/layout/trailing_whitespace.rb, line 36
def autocorrect(range)
  ->(corrector) { corrector.remove(range) }
end
investigate(processed_source) click to toggle source
# File lib/rubocop/cop/layout/trailing_whitespace.rb, line 22
def investigate(processed_source)
  heredoc_ranges = extract_heredoc_ranges(processed_source.ast)
  processed_source.lines.each_with_index do |line, index|
    next unless line.end_with?(' ', "\t")
    next if skip_heredoc? && inside_heredoc?(heredoc_ranges, index + 1)

    range = source_range(processed_source.buffer,
                         index + 1,
                         (line.rstrip.length)...(line.length))

    add_offense(range, location: range)
  end
end

Private Instance Methods

extract_heredoc_ranges(ast) click to toggle source
# File lib/rubocop/cop/layout/trailing_whitespace.rb, line 50
def extract_heredoc_ranges(ast)
  return [] unless ast

  ast.each_node(:str, :dstr, :xstr).select(&:heredoc?).map do |node|
    body = node.location.heredoc_body
    (body.first_line...body.last_line)
  end
end
inside_heredoc?(heredoc_ranges, line_number) click to toggle source
# File lib/rubocop/cop/layout/trailing_whitespace.rb, line 46
def inside_heredoc?(heredoc_ranges, line_number)
  heredoc_ranges.any? { |r| r.include?(line_number) }
end
skip_heredoc?() click to toggle source
# File lib/rubocop/cop/layout/trailing_whitespace.rb, line 42
def skip_heredoc?
  cop_config.fetch('AllowInHeredoc', false)
end