forked from zerohistory/toystore
/
identity_map.rb
106 lines (87 loc) · 2.19 KB
/
identity_map.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
module Toy
def self.identity_map
Thread.current[:toystore_identity_map] ||= {}
end
module IdentityMap
extend ActiveSupport::Concern
included do
identity_map_on
end
module ClassMethods
def identity_map
Toy.identity_map
end
def identity_map_on?
@identity_map_on == true
end
def identity_map_off?
!identity_map_on?
end
def identity_map_on
@identity_map_on = true
end
def identity_map_off
@identity_map_on = false
end
def without_identity_map(&block)
begin
original_identity_map_on = @identity_map_on
identity_map_off
yield
ensure
@identity_map_on = original_identity_map_on
end
end
def get(id)
get_from_identity_map(id) || super
end
def get_from_identity_map(id)
return nil unless identity_map_on?
if record = identity_map[id]
log_operation(:img, self.name, adapter, id)
record
end
end
def load(id, attrs)
return nil if attrs.nil?
if instance = identity_map[id]
instance
else
super.tap { |doc| doc.add_to_identity_map }
end
end
end
def identity_map
Toy.identity_map
end
def save(*)
super.tap do |result|
add_to_identity_map if result
end
end
def delete(*)
super.tap { remove_from_identity_map }
end
def add_to_identity_map
return unless self.class.identity_map_on?
identity_map[id] = self
log_operation(:ims, self.class.name, adapter, id)
end
def remove_from_identity_map
return unless self.class.identity_map_on?
identity_map.delete(id)
log_operation(:imd, self.class.name, adapter, id)
end
private
def has_embedded_objects?
self.class.embedded_lists.any?
end
def each_embedded_object(&block)
if has_embedded_objects?
self.class.embedded_lists.keys.inject([]) do |objects, name|
objects.concat(send(name).to_a.compact)
end.each { |object| block.call(object) }
end
end
end
end