Sha256: 092baaa7ecbc3573ec39928bd22b5a4c18111debae7cfaf184326a17c5bc1f35

Contents?: true

Size: 1.34 KB

Versions: 156

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # Prefer `equal?` over `==` when comparing `object_id`.
      #
      # `Object#equal?` is provided to compare objects for identity, and in contrast
      # `Object#==` is provided for the purpose of doing value comparison.
      #
      # @example
      #   # bad
      #   foo.object_id == bar.object_id
      #
      #   # good
      #   foo.equal?(bar)
      #
      class IdentityComparison < Base
        extend AutoCorrector

        MSG = 'Use `equal?` instead `==` when comparing `object_id`.'
        RESTRICT_ON_SEND = %i[==].freeze

        def on_send(node)
          return unless compare_between_object_id_by_double_equal?(node)

          add_offense(node) do |corrector|
            receiver = node.receiver.receiver
            argument = node.first_argument.receiver
            return unless receiver && argument

            replacement = "#{receiver.source}.equal?(#{argument.source})"

            corrector.replace(node, replacement)
          end
        end

        private

        def compare_between_object_id_by_double_equal?(node)
          object_id_method?(node.receiver) && object_id_method?(node.first_argument)
        end

        def object_id_method?(node)
          node.send_type? && node.method?(:object_id)
        end
      end
    end
  end
end

Version data entries

156 entries across 155 versions & 16 rubygems

Version Path
rubocop-1.74.0 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.73.2 lib/rubocop/cop/lint/identity_comparison.rb
siteimprove_api_client-1.0.1 vendor/bundle/ruby/3.2.0/gems/rubocop-1.73.1/lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.73.1 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.73.0 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.72.2 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.72.1 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.72.0 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.71.2 lib/rubocop/cop/lint/identity_comparison.rb
tailscale_middleware-0.0.3 vendor/cache/ruby/3.4.0/gems/rubocop-1.71.1/lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.71.1 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.71.0 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.70.0 lib/rubocop/cop/lint/identity_comparison.rb
minato_ruby_api_client-0.2.2 vendor/bundle/ruby/3.2.0/gems/rubocop-1.64.1/lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.69.2 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.69.1 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.69.0 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.68.0 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.67.0 lib/rubocop/cop/lint/identity_comparison.rb
rubocop-1.66.1 lib/rubocop/cop/lint/identity_comparison.rb