diff --git a/lib/active_model/serializer/caching.rb b/lib/active_model/serializer/caching.rb index 850c346b..0f1fffb2 100644 --- a/lib/active_model/serializer/caching.rb +++ b/lib/active_model/serializer/caching.rb @@ -1,3 +1,5 @@ +# TODO(BF): refactor file to be smaller +# rubocop:disable Metrics/ModuleLength module ActiveModel class Serializer UndefinedCacheKey = Class.new(StandardError) @@ -206,12 +208,18 @@ module ActiveModel end end - # Get attributes from @cached_attributes - # @return [Hash] cached attributes - # def cached_attributes(fields, adapter_instance) - def cached_fields(fields, adapter_instance) - cache_check(adapter_instance) do - attributes(fields) + def cached_attributes(fields, cached_attributes, adapter_instance) + if self.class.cache_enabled? + key = cache_key(adapter_instance) + cached_attributes.fetch(key) do + cache_check(adapter_instance) do + attributes(fields) + end + end + else + cache_check(adapter_instance) do + attributes(fields) + end end end @@ -331,3 +339,4 @@ module ActiveModel end end end +# rubocop:enable Metrics/ModuleLength diff --git a/lib/active_model_serializers/adapter/attributes.rb b/lib/active_model_serializers/adapter/attributes.rb index 6c903afe..56a155c3 100644 --- a/lib/active_model_serializers/adapter/attributes.rb +++ b/lib/active_model_serializers/adapter/attributes.rb @@ -32,7 +32,8 @@ module ActiveModelSerializers end def serializable_hash_for_single_resource(options) - resource = resource_object_for(options) + cached_attributes = instance_options[:cached_attributes] || {} + resource = serializer.cached_attributes(options[:fields], cached_attributes, self) relationships = resource_relationships(options) resource.merge(relationships) end @@ -60,18 +61,6 @@ module ActiveModelSerializers relationship_value end - - def resource_object_for(options) - if serializer.class.cache_enabled? - cached_attributes = instance_options[:cached_attributes] || {} - key = serializer.cache_key(self) - cached_attributes.fetch(key) do - serializer.cached_fields(options[:fields], self) - end - else - serializer.cached_fields(options[:fields], self) - end - end end end end