Sha256: a89e51dd2d92b5d07a5976d6e8844ec6e191a86a15a0598adde2c4ea14111318

Contents?: true

Size: 1.83 KB

Versions: 5

Compression:

Stored size: 1.83 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop looks for uses of block comments (=begin...=end).
      #
      # @example
      #   # bad
      #   =begin
      #   Multiple lines
      #   of comments...
      #   =end
      #
      #   # good
      #   # Multiple lines
      #   # of comments...
      #
      class BlockComments < Cop
        include RangeHelp

        MSG = 'Do not use block comments.'.freeze
        BEGIN_LENGTH = "=begin\n".length
        END_LENGTH = "\n=end".length

        def investigate(processed_source)
          processed_source.each_comment do |comment|
            next unless comment.document?

            add_offense(comment)
          end
        end

        def autocorrect(comment)
          eq_begin, eq_end, contents = parts(comment)

          lambda do |corrector|
            corrector.remove(eq_begin)
            unless contents.length.zero?
              corrector.replace(contents,
                                contents.source
                                  .gsub(/\A/, '# ')
                                  .gsub(/\n\n/, "\n#\n")
                                  .gsub(/\n(?=[^#])/, "\n# "))
            end
            corrector.remove(eq_end)
          end
        end

        private

        def parts(comment)
          expr = comment.loc.expression
          eq_begin = expr.resize(BEGIN_LENGTH)
          eq_end = eq_end_part(comment, expr)
          contents = range_between(eq_begin.end_pos, eq_end.begin_pos)
          [eq_begin, eq_end, contents]
        end

        def eq_end_part(comment, expr)
          if comment.text.chomp == comment.text
            range_between(expr.end_pos - END_LENGTH - 1, expr.end_pos - 2)
          else
            range_between(expr.end_pos - END_LENGTH, expr.end_pos)
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rubocop-0.68.1 lib/rubocop/cop/style/block_comments.rb
rubocop-0.68.0 lib/rubocop/cop/style/block_comments.rb
rubocop-0.67.2 lib/rubocop/cop/style/block_comments.rb
rubocop-0.67.1 lib/rubocop/cop/style/block_comments.rb
rubocop-0.67.0 lib/rubocop/cop/style/block_comments.rb