Skip to content

Remove unnecessary Serializer#cached_fields; Extracted cached_attributes #1765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 1, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions lib/active_model/serializer/caching.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# TODO(BF): refactor file to be smaller
# rubocop:disable Metrics/ModuleLength
module ActiveModel
class Serializer
UndefinedCacheKey = Class.new(StandardError)
Expand Down Expand Up @@ -206,12 +208,18 @@ def object_cache_key(serializer, adapter_instance)
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

Expand Down Expand Up @@ -331,3 +339,4 @@ def object_cache_key
end
end
end
# rubocop:enable Metrics/ModuleLength
15 changes: 2 additions & 13 deletions lib/active_model_serializers/adapter/attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ def serializable_hash_for_collection(options)
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
Expand Down Expand Up @@ -60,18 +61,6 @@ def relationship_value_for(association, options)

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