forked from cjheath/activefacts-api
/
comparable_hash_key.rb
83 lines (73 loc) · 1.85 KB
/
comparable_hash_key.rb
1
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#
# ActiveFacts Runtime API
# InstanceIndex class
#
# Copyright (c) 2009 Clifford Heath. Read the LICENSE file.
#
module ActiveFacts
module API
# ComparableHashKey provides a way to compare hashes with nil values.
class ComparableHashKey
# Key value
attr_reader :value
# Initialize an instance index key base on a hash.
def initialize(hash)
@value = flatten_key(hash)
end
# Compare an instance index key with another.
#
# Keys containing nil values will be compared using their string
# representation. (see inspect)
def <=>(other)
if !contains_nil?(@value) && !contains_nil?(other.value)
result = @value <=> other.value rescue nil
if result.nil?
result = @value.inspect <=> other.value.inspect
end
result
else
@value.inspect <=> other.value.inspect
end
end
# Checks if arr contains a nil value.
def contains_nil?(arr)
if arr.class.ancestors.include?(Array)
arr.any? do |el|
if el.nil?
true
else
contains_nil?(el)
end
end
else
arr.nil?
end
end
def ==(other)
@value == other.value
end
def eql?(other)
if self.class == other.class
self == other
else
false
end
end
def hash
@value.hash
end
private
# Any entity contained in `key` will be changed into its identifying role
# values.
def flatten_key(key)
if key.is_a?(Array)
key.map { |identifier| flatten_key(identifier) }
elsif key.respond_to?(:identifying_role_values)
key.identifying_role_values
else
key
end
end
end
end
end