Sha256: 03f6f642744601cad9bcef487824d731e7622cc7337a027947a195ff59c87a09

Contents?: true

Size: 806 Bytes

Versions: 13

Compression:

Stored size: 806 Bytes

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for comparison of something with nil using ==.
      #
      # @example
      #
      #   # bad
      #   if x == nil
      #   end
      #
      #   # good
      #   if x.nil?
      #   end
      class NilComparison < Cop
        MSG = 'Prefer the use of the `nil?` predicate.'.freeze

        def_node_matcher :nil_comparison?, '(send _ {:== :===} nil)'

        def on_send(node)
          nil_comparison?(node) do
            add_offense(node, location: :selector)
          end
        end

        def autocorrect(node)
          new_code = node.source.sub(/\s*={2,3}\s*nil/, '.nil?')
          ->(corrector) { corrector.replace(node.source_range, new_code) }
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
rubocop-0.58.2 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.58.1 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.58.0 lib/rubocop/cop/style/nil_comparison.rb
vagrant-packet-0.1.1 vendor/bundle/ruby/2.4.0/gems/rubocop-0.57.2/lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.57.2 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.57.1 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.57.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.56.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.55.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.54.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.53.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.52.1 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.52.0 lib/rubocop/cop/style/nil_comparison.rb