identity_cache 0.0.2 → 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,71 +0,0 @@
1
- require 'monitor'
2
-
3
- module IdentityCache
4
- class MemoizedCacheProxy
5
- attr_writer :memcache
6
-
7
- def initialize(memcache = nil)
8
- @memcache = memcache || Rails.cache
9
- @key_value_maps = Hash.new {|h, k| h[k] = {} }
10
- end
11
-
12
- def memoized_key_values
13
- @key_value_maps[Thread.current.object_id]
14
- end
15
-
16
- def with_memoization(&block)
17
- Thread.current[:memoizing_idc] = true
18
- yield
19
- ensure
20
- clear_memoization
21
- Thread.current[:memoizing_idc] = false
22
- end
23
-
24
- def write(key, value)
25
- memoized_key_values[key] = value if memoizing?
26
- @memcache.write(key, value)
27
- end
28
-
29
- def read(key)
30
- if memoizing?
31
- memoized_key_values[key] ||= @memcache.read(key)
32
- else
33
- @memcache.read(key)
34
- end
35
- end
36
-
37
- def delete(key)
38
- memoized_key_values.delete(key) if memoizing?
39
- @memcache.delete(key)
40
- end
41
-
42
- def read_multi(*keys)
43
- hash = {}
44
-
45
- if memoizing?
46
- keys.reduce({}) do |hash, key|
47
- hash[key] = memoized_key_values[key] if memoized_key_values[key].present?
48
- hash
49
- end
50
- end
51
-
52
- missing_keys = keys - hash.keys
53
- hash.merge(@memcache.read_multi(*missing_keys))
54
- end
55
-
56
- def clear
57
- clear_memoization
58
- @memcache.clear
59
- end
60
-
61
- private
62
-
63
- def clear_memoization
64
- @key_value_maps.delete(Thread.current.object_id)
65
- end
66
-
67
- def memoizing?
68
- Thread.current[:memoizing_idc]
69
- end
70
- end
71
- end