class RuboCop::Cop::Style::CommentedKeyword

Checks for comments put on the same line as some keywords. These keywords are: ‘class`, `module`, `def`, `begin`, `end`.

Note that some comments (‘:nodoc:`, `:yields:`, `rubocop:disable` and `rubocop:todo`) and RBS::Inline annotation comments are allowed.

Autocorrection removes comments from ‘end` keyword and keeps comments for `class`, `module`, `def` and `begin` above the keyword.

@safety

Autocorrection is unsafe because it may remove a comment that is
meaningful.

@example

# bad
if condition
  statement
end # end if

# bad
class X # comment
  statement
end

# bad
def x; end # comment

# good
if condition
  statement
end

# good
class X # :nodoc:
  y
end

Constants

ALLOWED_COMMENTS
ALLOWED_COMMENT_REGEXES
KEYWORDS
KEYWORD_REGEXES
MSG
REGEXP

Public Instance Methods

on_new_investigation() click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 60
def on_new_investigation
  processed_source.comments.each do |comment|
    next unless offensive?(comment) && (match = source_line(comment).match(REGEXP))

    register_offense(comment, match[:keyword])
  end
end

Private Instance Methods

offensive?(comment) click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 83
def offensive?(comment)
  line = source_line(comment)
  return false if rbs_inline_annotation?(line, comment)

  KEYWORD_REGEXES.any? { |r| r.match?(line) } &&
    ALLOWED_COMMENT_REGEXES.none? { |r| r.match?(line) }
end
rbs_inline_annotation?(line, comment) click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 95
def rbs_inline_annotation?(line, comment)
  comment.text.start_with?('#:') && line.start_with?(/\A\s*def\s/)
end
register_offense(comment, matched_keyword) click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 70
def register_offense(comment, matched_keyword)
  add_offense(comment, message: format(MSG, keyword: matched_keyword)) do |corrector|
    range = range_with_surrounding_space(comment.source_range, newlines: false)
    corrector.remove(range)

    unless matched_keyword == 'end'
      corrector.insert_before(
        range.source_buffer.line_range(comment.loc.line), "#{comment.text}\n"
      )
    end
  end
end
source_line(comment) click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 91
def source_line(comment)
  comment.source_range.source_line
end