Skip to content

Commit f2f747e

Browse files
committed
Merge pull request #1765 from bf4/serializer_cleanup_3
Remove unnecessary Serializer#cached_fields; Extracted cached_attributes
2 parents fcfbc0d + 385abb4 commit f2f747e

File tree

2 files changed

+17
-19
lines changed

2 files changed

+17
-19
lines changed

lib/active_model/serializer/caching.rb

Lines changed: 15 additions & 6 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,12 +208,18 @@ def object_cache_key(serializer, adapter_instance)
206208
end
207209
end
208210

209-
# Get attributes from @cached_attributes
210-
# @return [Hash] cached attributes
211-
# def cached_attributes(fields, adapter_instance)
212-
def cached_fields(fields, adapter_instance)
213-
cache_check(adapter_instance) do
214-
attributes(fields)
211+
def cached_attributes(fields, 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(fields)
217+
end
218+
end
219+
else
220+
cache_check(adapter_instance) do
221+
attributes(fields)
222+
end
215223
end
216224
end
217225

@@ -331,3 +339,4 @@ def object_cache_key
331339
end
332340
end
333341
end
342+
# rubocop:enable Metrics/ModuleLength

lib/active_model_serializers/adapter/attributes.rb

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

3434
def serializable_hash_for_single_resource(options)
35-
resource = resource_object_for(options)
35+
cached_attributes = instance_options[:cached_attributes] || {}
36+
resource = serializer.cached_attributes(options[:fields], cached_attributes, self)
3637
relationships = resource_relationships(options)
3738
resource.merge(relationships)
3839
end
@@ -60,18 +61,6 @@ def relationship_value_for(association, options)
6061

6162
relationship_value
6263
end
63-
64-
def resource_object_for(options)
65-
if serializer.class.cache_enabled?
66-
cached_attributes = instance_options[:cached_attributes] || {}
67-
key = serializer.cache_key(self)
68-
cached_attributes.fetch(key) do
69-
serializer.cached_fields(options[:fields], self)
70-
end
71-
else
72-
serializer.cached_fields(options[:fields], self)
73-
end
74-
end
7564
end
7665
end
7766
end

0 commit comments

Comments
 (0)