Sha256: 330a9ccc6f7bed2f0c638349800acf5ac97c4669fadc0b47562007e1c31037a1

Contents?: true

Size: 1.72 KB

Versions: 4

Compression:

Stored size: 1.72 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # 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
      # (`:nodoc:`, `:yields:`, `rubocop:disable` and `rubocop:todo`)
      # 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
      class CommentedKeyword < Cop
        MSG = 'Do not place comments on the same line as the ' \
              '`%<keyword>s` keyword.'

        def investigate(processed_source)
          processed_source.each_comment do |comment|
            add_offense(comment) if offensive?(comment)
          end
        end

        private

        KEYWORDS = %w[begin class def end module].freeze
        ALLOWED_COMMENTS = %w[
          :nodoc:
          :yields:
          rubocop:disable
          rubocop:todo
        ].freeze

        def offensive?(comment)
          line = line(comment)
          KEYWORDS.any? { |word| /^\s*#{word}\s/.match?(line) } &&
            ALLOWED_COMMENTS.none? { |c| /#\s*#{c}/.match?(line) }
        end

        def message(comment)
          keyword = line(comment).match(/(\S+).*#/)[1]
          format(MSG, keyword: keyword)
        end

        def line(comment)
          comment.location.expression.source_line
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
rubocop-0.87.1 lib/rubocop/cop/style/commented_keyword.rb
rubocop-0.87.0 lib/rubocop/cop/style/commented_keyword.rb
rubocop-0.86.0 lib/rubocop/cop/style/commented_keyword.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/style/commented_keyword.rb