class RuboCop::Cop::Style::CommentedKeyword
This cop checks for comments put on the same line as some keywords. These keywords are: `begin`, `class`, `def`, `end`, `module`.
Note that some comments (such as `:nodoc:` and `rubocop:disable`) are allowed.
@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
- KEYWORDS
- MSG
Public Instance Methods
investigate(processed_source)
click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 38 def investigate(processed_source) heredoc_lines = extract_heredoc_lines(processed_source.ast) processed_source.lines.each_with_index do |line, index| next if heredoc_lines.any? { |r| r.include?(index + 1) } next unless offensive?(line) range = source_range(processed_source.buffer, index + 1, (line.index('#'))...(line.length)) add_offense(range, location: range) end end
Private Instance Methods
extract_heredoc_lines(ast)
click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 69 def extract_heredoc_lines(ast) return [] unless ast ast.each_node.with_object([]) do |node, heredocs| next unless node.location.is_a?(Parser::Source::Map::Heredoc) body = node.location.heredoc_body heredocs << (body.first_line...body.last_line) end end
message(node)
click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 63 def message(node) line = node.source_line keyword = /^\s*(\S+).*#/.match(line)[1] format(MSG, keyword) end
offensive?(line)
click to toggle source
# File lib/rubocop/cop/style/commented_keyword.rb, line 58 def offensive?(line) KEYWORDS.any? { |k| line =~ /^\s*#{k}\s+.*#/ } && ALLOWED_COMMENTS.none? { |c| line =~ /#\s*#{c}/ } end