forked from instructure/canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_cache.rb
More file actions
143 lines (127 loc) · 4.43 KB
/
Copy pathmodel_cache.rb
File metadata and controls
143 lines (127 loc) · 4.43 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# Copyright (C) 2012 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# on-demand in-memory model caching for those times where the rails query
# cache can't help you, like in this contrived example:
#
# # given:
#
# class Foo < ActiveRecord::Base
# has_many :bars
# end
#
# class Bar < ActiveRecord::Base
# belongs_to :foo
# def something!
# update_attribute :stuff, "my foo is: #{foo.name}"
# end
# end
#
# # if you do:
# foo.bars.each(&:something!)
#
# # then by default, AR loads each bar's foo separately and won't use the
# # query cache, since each update blows it away.
#
# granted, the example is a bit contrived, as preloading would be one possible
# solution. ModelCache is useful for those times when preloading is just not
# feasible. See Conversation and ConversatonParticipant for real-world usage.
module ModelCache
module ClassMethods
# e.g. use this to cache calls to ConversationParticipant#conversation,
# no matter how those conversation_participants were loaded
def cacheable_method(method, options={})
options[:cache_name] ||= method.to_s.pluralize.to_sym
options[:key_method] ||= "#{method}_id"
options[:key_lookup] ||= :id
options[:type] ||= :instance
# ensure the target class is ModelCache-aware, and set up the :id lookup
target_klass = reflections[method.to_s].klass
raise "`#{target_klass}` needs to `include ModelCache` before you can make `#{self}##{method}` cacheable" unless target_klass.included_modules.include?(ModelCache)
unless ModelCache.keys[target_klass.name].include?(options[:key_lookup])
ModelCache.keys[target_klass.name] << options[:key_lookup]
end
ModelCache.make_cacheable self, method, options
end
end
module InstanceMethods
def add_to_caches
return unless cache = ModelCache[self.class.name.underscore.pluralize.to_sym]
cache.keys.each do |key|
cache[key][send(key)] = self
end
end
def update_in_caches
return unless cache = ModelCache[self.class.name.underscore.pluralize.to_sym]
cache.keys.each do |key|
if send("#{key}_changed?")
cache[key][send(key)] = self
cache[key].delete(send("#{key}_was"))
end
end
end
end
def self.with_cache(lookups)
@cache = lookups.inject({}){ |h, (k, v)| h[k] = prepare_lookups(v); h }
yield
ensure
@cache = nil
end
def self.[](cache_name)
return nil unless @cache
@cache[cache_name] || {}
end
def self.keys
@keys ||= Hash.new{ |h, k| h[k] = [] }
end
def self.prepare_lookups(records)
return records if records.is_a?(Hash)
return {} if records.empty?
keys[records.first.class.name].inject({}) do |h, k|
h[k] = records.index_by(&k)
h
end
end
def self.make_cacheable(klass, method, options={})
options[:type] ||= :class
options[:cache_name] ||= klass.name.underscore.pluralize.to_sym
options[:key_lookup] ||= method
orig_method = "super"
alias_method = nil
key_value = options[:key_method] || "args.first"
# if extra args are provided, we should clear out the current value
# (e.g. if you call c.user(:lock => true) )
expected_args = options[:key_method] ? 0 : 1
maybe_reset = "cache[#{key_value}] = #{orig_method} if args.size > #{expected_args}"
klass.send(options[:type] == :instance ? :class_eval : :instance_eval, <<-CODE, __FILE__, __LINE__+1)
def #{method}(*args)
if cache = ModelCache[#{options[:cache_name].inspect}] and cache = cache[#{options[:key_lookup].inspect}]
#{maybe_reset}
cache[#{key_value}]
else
#{orig_method}
end
end
#{alias_method}
CODE
end
def self.included(klass)
klass.send :include, InstanceMethods
klass.extend ClassMethods
klass.after_create :add_to_caches
klass.after_update :update_in_caches
end
end