Skip to content

Commit ba23de6

Browse files
committed
Complete extracting to Serializer#cached_attributes
1 parent 96750b2 commit ba23de6

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

lib/active_model/serializer/caching.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# TODO(BF): refactor file to be smaller
2+
# rubocop:disable Metrics/ModuleLength
13
module ActiveModel
24
class Serializer
35
UndefinedCacheKey = Class.new(StandardError)
@@ -206,6 +208,21 @@ def object_cache_key(serializer, adapter_instance)
206208
end
207209
end
208210

211+
def cached_attributes(options, cached_attributes, adapter_instance)
212+
if self.class.cache_enabled?
213+
key = cache_key(adapter_instance)
214+
cached_attributes.fetch(key) do
215+
cache_check(adapter_instance) do
216+
attributes(options[:fields])
217+
end
218+
end
219+
else
220+
cache_check(adapter_instance) do
221+
attributes(options[:fields])
222+
end
223+
end
224+
end
225+
209226
def cache_check(adapter_instance)
210227
if self.class.cache_enabled?
211228
self.class.cache_store.fetch(cache_key(adapter_instance), self.class._cache_options) do
@@ -322,3 +339,4 @@ def object_cache_key
322339
end
323340
end
324341
end
342+
# rubocop:enable Metrics/ModuleLength

lib/active_model_serializers/adapter/attributes.rb

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,20 +32,8 @@ def serializable_hash_for_collection(options)
3232
end
3333

3434
def serializable_hash_for_single_resource(options)
35-
resource =
36-
if serializer.class.cache_enabled?
37-
cached_attributes = instance_options[:cached_attributes] || {}
38-
key = serializer.cache_key(self)
39-
cached_attributes.fetch(key) do
40-
serializer.cache_check(self) do
41-
serializer.attributes(options[:fields])
42-
end
43-
end
44-
else
45-
serializer.cache_check(self) do
46-
serializer.attributes(options[:fields])
47-
end
48-
end
35+
cached_attributes = instance_options[:cached_attributes] || {}
36+
resource = serializer.cached_attributes(options, cached_attributes, self)
4937
relationships = resource_relationships(options)
5038
resource.merge(relationships)
5139
end

0 commit comments

Comments
 (0)