-
Notifications
You must be signed in to change notification settings - Fork 63
/
caching_connection.rb
80 lines (68 loc) · 1.6 KB
/
caching_connection.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
module ActiveFedora
class CachingConnection < Ldp::Client
def initialize(host)
super
@cache = {}
@cache_enabled = false
end
def get(url, options = {})
if @cache_enabled
cache_resource(url) { super }
else
super
end
end
def post(*)
clear_cache if @cache_enabled
super
end
def put(*)
clear_cache if @cache_enabled
super
end
def patch(*)
clear_cache if @cache_enabled
super
end
# Enable the cache within the block.
def cache
old, @cache_enabled = @cache_enabled, true
yield
ensure
@cache_enabled = old
clear_cache unless @cache_enabled
end
def enable_cache!
@cache_enabled = true
end
def disable_cache!
@cache_enabled = false
end
# Disable the query cache within the block.
def uncached
old, @cache_enabled = @cache_enabled, false
yield
ensure
@cache_enabled = old
end
def clear_cache
@cache.clear
end
private
def log(url)
ActiveSupport::Notifications.instrument("ldp.active_fedora",
id: url, name: "Load LDP", ldp_service: object_id) { yield }
end
def cache_resource(url, &block)
result =
if @cache.key?(url)
ActiveSupport::Notifications.instrument("ldp.active_fedora",
id: url, name: "CACHE", ldp_service: object_id)
@cache[url]
else
@cache[url] = log(url) { yield }
end
result.dup
end
end
end