Sha256: 842d32131a3067ada6d9fc7a05b29a3561fd7eff9ef9df2b822f3e56d95e874b

Contents?: true

Size: 1.01 KB

Versions: 20

Compression:

Stored size: 1.01 KB

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.'

        # @!method id_as_hash_key?(node)
        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

20 entries across 20 versions & 3 rubygems

Version Path
rubocop-1.21.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.20.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.19.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rails_mini_profiler-0.2.0 vendor/bundle/ruby/3.0.0/gems/rubocop-1.18.3/lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.19.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.18.4 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.18.3 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.18.2 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.18.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.18.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.17.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.16.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.16.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.15.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
cocRb-0.1.0 .bundle/ruby/3.0.0/gems/rubocop-1.14.0/lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.14.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.13.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.12.1 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.12.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb
rubocop-1.11.0 lib/rubocop/cop/lint/hash_compare_by_identity.rb