Sha256: ecb84ce14fd9842b251050d8c1ec5cb4027c6100642f883bd321de7c197d8295

Contents?: true

Size: 997 Bytes

Versions: 21

Compression:

Stored size: 997 Bytes

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # Prefer using `Hash#compare_by_identity` than using `object_id` for hash keys.
      #
      # This cop is marked as unsafe as a hash possibly can contain other keys
      # besides `object_id`s.
      #
      # @example
      #   # bad
      #   hash = {}
      #   hash[foo.object_id] = :bar
      #   hash.key?(baz.object_id)
      #
      #   # good
      #   hash = {}.compare_by_identity
      #   hash[foo] = :bar
      #   hash.key?(baz)
      #
      class HashCompareByIdentity < Base
        RESTRICT_ON_SEND = %i[key? has_key? fetch [] []=].freeze

        MSG = 'Use `Hash#compare_by_identity` instead of using `object_id` for keys.'

        def_node_matcher :id_as_hash_key?, <<~PATTERN
          (send _ {:key? :has_key? :fetch :[] :[]=} (send _ :object_id) ...)
        PATTERN

        def on_send(node)
          add_offense(node) if id_as_hash_key?(node)
        end
      end
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
rubocop-1.10.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.9.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.9.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.8.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.8.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.7.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.6.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.6.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.5.2 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.5.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.5.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.4.2 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.4.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.4.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.3.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.3.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.2.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.1.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.0.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-0.93.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb