forked from zerohistory/toystore
-
Notifications
You must be signed in to change notification settings - Fork 12
/
identity_map.rb
81 lines (64 loc) · 1.61 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
module Toy
module IdentityMap
extend ActiveSupport::Concern
def self.enabled=(flag)
Thread.current[:toystore_identity_map_enabled] = flag
end
def self.enabled
Thread.current[:toystore_identity_map_enabled]
end
def self.enabled?
enabled == true
end
def self.repository
Thread.current[:toystore_identity_map] ||= {}
end
def self.clear
repository.clear
end
def self.include?(object)
repository.keys.include?(object.id)
end
def self.use
old, self.enabled = enabled, true
yield if block_given?
ensure
self.enabled = old
clear
end
def self.without
old, self.enabled = enabled, false
yield if block_given?
ensure
self.enabled = old
end
module ClassMethods
def get(id, options = nil)
get_from_identity_map(id) || super
end
def get_from_identity_map(id)
IdentityMap.repository[id] if IdentityMap.enabled?
end
private :get_from_identity_map
def load(id, attrs)
if IdentityMap.enabled? && instance = IdentityMap.repository[id]
instance
else
super.tap { |doc| doc.add_to_identity_map }
end
end
end
def save(options={})
super.tap { |result| add_to_identity_map if result }
end
def delete
super.tap { remove_from_identity_map }
end
def add_to_identity_map
IdentityMap.repository[id] = self if IdentityMap.enabled?
end
def remove_from_identity_map
IdentityMap.repository.delete(id) if IdentityMap.enabled?
end
end
end