Sha256: cb7a92caa2c2127ceeeab41e56f890af77e9761926a74b9876a99a7b7df08f43

Contents?: true

Size: 905 Bytes

Versions: 4

Compression:

Stored size: 905 Bytes

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # Checks for regexp literals used as `match-current-line`.
      # If a regexp literal is in condition, the regexp matches `$_` implicitly.
      #
      # @example
      #   # bad
      #   if /foo/
      #     do_something
      #   end
      #
      #   # good
      #   if /foo/ =~ $_
      #     do_something
      #   end
      class RegexpAsCondition < Base
        extend AutoCorrector

        MSG = 'Do not use regexp literal as a condition. ' \
              'The regexp literal matches `$_` implicitly.'

        def on_match_current_line(node)
          return if node.ancestors.none?(&:conditional?)
          return if part_of_ignored_node?(node)

          add_offense(node) { |corrector| corrector.replace(node, "#{node.source} =~ $_") }

          ignore_node(node)
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubocop-1.70.0 lib/rubocop/cop/lint/regexp_as_condition.rb
rubocop-1.69.2 lib/rubocop/cop/lint/regexp_as_condition.rb
rubocop-1.69.1 lib/rubocop/cop/lint/regexp_as_condition.rb
rubocop-1.69.0 lib/rubocop/cop/lint/regexp_as_condition.rb