Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/rr/core_ext/hash.rb

Direct Known Subclasses

RR::HashWithObjectIdKey

Instance Method Summary collapse

Instance Method Details

#wildcard_match?(other) ⇒ Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rr/core_ext/hash.rb', line 2

def wildcard_match?(other)
  return false unless other.is_a?(Hash)

  return false if size != other.size

  wildcards, exacts = partition {|key, _| key.respond_to?(:wildcard_match?)}
  other = other.dup
  exacts.each do |key, value|
    return false unless other.key?(key)
    other_value = other.delete(key)
    if value.respond_to?(:wildcard_match?)
      return false unless value.wildcard_match?(other_value)
    else
      return false unless value == other_value
    end
  end
  # TODO: Add support for the following case:
  #   {
  #      is_a(Symbol) => anything,
  #      is_a(Symbol) => 1,
  #   }.wildcard_match?(d: 1, c: 3)
  wildcards.each do |key, value|
    found = false
    other.each do |other_key, other_value|
      next unless key.wildcard_match?(other_key)
      if value.respond_to?(:wildcard_match?)
        next unless value.wildcard_match?(other_value)
      else
        next unless value == other_value
      end
      other.delete(other_key)
      found = true
      break
    end
    return false unless found
  end

  true
end