Sha256: 0672fcd54a09ddf8c91dcbd9e86566d0b623dfb29addae762568db667b0a44de

Contents?: true

Size: 1.75 KB

Versions: 16

Compression:

Stored size: 1.75 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for comparison of something with nil using `==` and
      # `nil?`.
      #
      # Supported styles are: predicate, comparison.
      #
      # @example EnforcedStyle: predicate (default)
      #
      #   # bad
      #   if x == nil
      #   end
      #
      #   # good
      #   if x.nil?
      #   end
      #
      # @example EnforcedStyle: comparison
      #
      #   # bad
      #   if x.nil?
      #   end
      #
      #   # good
      #   if x == nil
      #   end
      #
      class NilComparison < Cop
        include ConfigurableEnforcedStyle

        PREDICATE_MSG = 'Prefer the use of the `nil?` predicate.'
        EXPLICIT_MSG = 'Prefer the use of the `==` comparison.'

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

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

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

        private

        def message(_node)
          prefer_comparison? ? EXPLICIT_MSG : PREDICATE_MSG
        end

        def style_check?(node, &block)
          if prefer_comparison?
            nil_check?(node, &block)
          else
            nil_comparison?(node, &block)
          end
        end

        def prefer_comparison?
          style == :comparison
        end
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 3 rubygems

Version Path
rubocop-0.89.1 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.89.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.88.0 lib/rubocop/cop/style/nil_comparison.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.87.1 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.87.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.86.0 lib/rubocop/cop/style/nil_comparison.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/style/nil_comparison.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/style/nil_comparison.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.85.1 lib/rubocop/cop/style/nil_comparison.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.85.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.84.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.83.0 lib/rubocop/cop/style/nil_comparison.rb
rubocop-0.82.0 lib/rubocop/cop/style/nil_comparison.rb