Skip to content

Commit 1e10c20

Browse files
committed
Consolidate and simplify caching code
1 parent e2ded59 commit 1e10c20

File tree

9 files changed

+283
-360
lines changed

9 files changed

+283
-360
lines changed

lib/active_model/serializer/caching.rb

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
module ActiveModel
22
class Serializer
3+
UndefinedCacheKey = Class.new(StandardError)
34
module Caching
45
extend ActiveSupport::Concern
56

@@ -145,6 +146,172 @@ def fragment_cache_enabled?
145146
perform_caching? && cache_store &&
146147
(_cache_only && !_cache_except || !_cache_only && _cache_except)
147148
end
149+
150+
# Read cache from cache_store
151+
# @return [Hash]
152+
def cache_read_multi(collection_serializer, adapter_instance, include_tree)
153+
return {} if ActiveModelSerializers.config.cache_store.blank?
154+
155+
keys = object_cache_keys(collection_serializer, adapter_instance, include_tree)
156+
157+
return {} if keys.blank?
158+
159+
ActiveModelSerializers.config.cache_store.read_multi(*keys)
160+
end
161+
162+
# Find all cache_key for the collection_serializer
163+
# @param serializers [ActiveModel::Serializer::CollectionSerializer]
164+
# @param adapter_instance [ActiveModelSerializers::Adapter::Base]
165+
# @param include_tree [ActiveModel::Serializer::IncludeTree]
166+
# @return [Array] all cache_key of collection_serializer
167+
def object_cache_keys(collection_serializer, adapter_instance, include_tree)
168+
cache_keys = []
169+
170+
collection_serializer.each do |serializer|
171+
cache_keys << object_cache_key(serializer, adapter_instance)
172+
173+
serializer.associations(include_tree).each do |association|
174+
if association.serializer.respond_to?(:each)
175+
association.serializer.each do |sub_serializer|
176+
cache_keys << object_cache_key(sub_serializer, adapter_instance)
177+
end
178+
else
179+
cache_keys << object_cache_key(association.serializer, adapter_instance)
180+
end
181+
end
182+
end
183+
184+
cache_keys.compact.uniq
185+
end
186+
187+
# @return [String, nil] the cache_key of the serializer or nil
188+
def object_cache_key(serializer, adapter_instance)
189+
return unless serializer.present? && serializer.object.present?
190+
191+
serializer.class.cache_enabled? ? serializer.cache_key(adapter_instance) : nil
192+
end
193+
end
194+
195+
# Get attributes from @cached_attributes
196+
# @return [Hash] cached attributes
197+
# def cached_attributes(fields, adapter_instance)
198+
def cached_fields(fields, adapter_instance)
199+
cache_check(adapter_instance) do
200+
attributes(fields)
201+
end
202+
end
203+
204+
def cache_check(adapter_instance)
205+
if self.class.cache_enabled?
206+
self.class.cache_store.fetch(cache_key(adapter_instance), self.class._cache_options) do
207+
yield
208+
end
209+
elsif self.class.fragment_cache_enabled?
210+
fetch_fragment_cache(adapter_instance)
211+
else
212+
yield
213+
end
214+
end
215+
216+
# 1. Create a CachedSerializer and NonCachedSerializer from the serializer class
217+
# 2. Serialize the above two with the given adapter
218+
# 3. Pass their serializations to the adapter +::fragment_cache+
219+
def fetch_fragment_cache(adapter_instance)
220+
# It will split the serializer into two, one that will be cached and one that will not
221+
222+
# Given a resource name
223+
# 1. Dynamically creates a CachedSerializer and NonCachedSerializer
224+
# for a given class 'name'
225+
# 2. Call
226+
# CachedSerializer.cache(serializer._cache_options)
227+
# CachedSerializer.fragmented(serializer)
228+
# NonCachedSerializer.cache(serializer._cache_options)
229+
# 3. Build a hash keyed to the +cached+ and +non_cached+ serializers
230+
# 4. Call +cached_attributes+ on the serializer class and the above hash
231+
# 5. Return the hash
232+
#
233+
# @example
234+
# When +name+ is <tt>User::Admin</tt>
235+
# creates the Serializer classes (if they don't exist).
236+
# CachedUser_AdminSerializer
237+
# NonCachedUser_AdminSerializer
238+
#
239+
serializer_class_name = self.class.name.gsub('::'.freeze, '_'.freeze)
240+
cached_serializer = _get_or_create_fragment_serializer "Cached#{serializer_class_name}"
241+
non_cached_serializer = _get_or_create_fragment_serializer "NonCached#{serializer_class_name}"
242+
243+
self.class._cache_options ||= {}
244+
self.class._cache_options[:key] = self.class._cache_key if self.class._cache_key
245+
cached_serializer.cache(self.class._cache_options)
246+
247+
cached_serializer.type(self.class._type)
248+
non_cached_serializer.type(self.class._type)
249+
250+
non_cached_serializer.fragmented(self)
251+
cached_serializer.fragmented(self)
252+
253+
# Given a hash of its cached and non-cached serializers
254+
# 1. Determine cached attributes from serializer class options
255+
# 2. Add cached attributes to cached Serializer
256+
# 3. Add non-cached attributes to non-cached Serializer
257+
attributes = self.class._attributes
258+
cache_only = self.class._cache_only
259+
cached_attributes = cache_only ? cache_only : attributes - self.class._cache_except
260+
non_cached_attributes = attributes - cached_attributes
261+
attributes_keys = self.class._attributes_keys
262+
263+
cached_attributes.each do |attribute|
264+
options = attributes_keys[attribute] || {}
265+
cached_serializer.attribute(attribute, options)
266+
end
267+
non_cached_attributes.each do |attribute|
268+
options = attributes_keys[attribute] || {}
269+
non_cached_serializer.attribute(attribute, options)
270+
end
271+
272+
# Get serializable hash from both
273+
cached_hash = ActiveModelSerializers::SerializableResource.new(
274+
object,
275+
serializer: cached_serializer,
276+
adapter: adapter_instance.class
277+
).serializable_hash
278+
non_cached_hash = ActiveModelSerializers::SerializableResource.new(
279+
object,
280+
serializer: non_cached_serializer,
281+
adapter: adapter_instance.class
282+
).serializable_hash
283+
284+
# Merge both results
285+
adapter_instance.fragment_cache(cached_hash, non_cached_hash)
286+
end
287+
288+
def _get_or_create_fragment_serializer(name)
289+
return Object.const_get(name) if Object.const_defined?(name)
290+
Object.const_set(name, Class.new(ActiveModel::Serializer))
291+
end
292+
293+
def cache_key(adapter_instance)
294+
return @cache_key if defined?(@cache_key)
295+
296+
parts = []
297+
parts << object_cache_key
298+
parts << adapter_instance.cached_name
299+
parts << self.class._cache_digest unless self.class._skip_digest?
300+
@cache_key = parts.join('/')
301+
end
302+
303+
# Use object's cache_key if available, else derive a key from the object
304+
# Pass the `key` option to the `cache` declaration or override this method to customize the cache key
305+
def object_cache_key
306+
if object.respond_to?(:cache_key)
307+
object.cache_key
308+
elsif (serializer_cache_key = (self.class._cache_key || self.class._cache_options[:key]))
309+
object_time_safe = object.updated_at
310+
object_time_safe = object_time_safe.strftime('%Y%m%d%H%M%S%9N') if object_time_safe.respond_to?(:strftime)
311+
"#{serializer_cache_key}/#{object.id}-#{object_time_safe}"
312+
else
313+
fail UndefinedCacheKey, "#{object.class} must define #cache_key, or the 'key:' option must be passed into '#{self.class}.cache'"
314+
end
148315
end
149316
end
150317
end

lib/active_model_serializers.rb

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
module ActiveModelSerializers
77
extend ActiveSupport::Autoload
88
autoload :Model
9-
autoload :CachedSerializer
10-
autoload :FragmentCache
119
autoload :Callbacks
1210
autoload :Deserialization
1311
autoload :SerializableResource

lib/active_model_serializers/adapter/attributes.rb

Lines changed: 12 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -25,33 +25,6 @@ def serializable_hash_for_collection(options)
2525
serializer.map { |s| Attributes.new(s, instance_options).serializable_hash(options) }
2626
end
2727

28-
# Read cache from cache_store
29-
# @return [Hash]
30-
def cache_read_multi
31-
return {} if ActiveModelSerializers.config.cache_store.blank?
32-
33-
keys = CachedSerializer.object_cache_keys(serializer, self, @include_tree)
34-
35-
return {} if keys.blank?
36-
37-
ActiveModelSerializers.config.cache_store.read_multi(*keys)
38-
end
39-
40-
# Set @cached_attributes
41-
def cache_attributes
42-
return if @cached_attributes.present?
43-
44-
@cached_attributes = cache_read_multi
45-
end
46-
47-
# Get attributes from @cached_attributes
48-
# @return [Hash] cached attributes
49-
def cached_attributes(cached_serializer)
50-
return yield unless cached_serializer.cached?
51-
52-
@cached_attributes.fetch(cached_serializer.cache_key(self)) { yield }
53-
end
54-
5528
def serializable_hash_for_single_resource(options)
5629
resource = resource_object_for(options)
5730
relationships = resource_relationships(options)
@@ -80,13 +53,20 @@ def include_meta(json)
8053
json
8154
end
8255

83-
def resource_object_for(options)
84-
cached_serializer = CachedSerializer.new(serializer)
56+
# Set @cached_attributes
57+
def cache_attributes
58+
return if @cached_attributes.present?
59+
60+
@cached_attributes = ActiveModel::Serializer.cache_read_multi(serializer, self, @include_tree)
61+
end
8562

86-
cached_attributes(cached_serializer) do
87-
cached_serializer.cache_check(self) do
88-
serializer.attributes(options[:fields])
63+
def resource_object_for(options)
64+
if serializer.class.cache_enabled?
65+
@cached_attributes.fetch(serializer.cache_key(self)) do
66+
serializer.cached_fields(options[:fields], self)
8967
end
68+
else
69+
serializer.cached_fields(options[:fields], self)
9070
end
9171
end
9272
end

lib/active_model_serializers/adapter/base.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def fragment_cache(cached_hash, non_cached_hash)
3636
end
3737

3838
def cache_check(serializer)
39-
CachedSerializer.new(serializer).cache_check(self) do
39+
serializer.cache_check(self) do
4040
yield
4141
end
4242
end

lib/active_model_serializers/cached_serializer.rb

Lines changed: 0 additions & 87 deletions
This file was deleted.

0 commit comments

Comments
 (0)