Adding Fragment Cache to AMS

It's an upgrade based on the new Cache implementation #693.
It allows to use the Rails conventions to cache
specific attributes or associations.
It's based on the Cache Composition implementation.
This commit is contained in:
João Moura
2015-02-03 21:57:02 -02:00
parent 48ed7cf9ba
commit 792fb8a905
19 changed files with 554 additions and 101 deletions

View File

@@ -1,3 +1,5 @@
require 'active_model/serializer/adapter/json_api/fragment_cache'
module ActiveModel
class Serializer
class Adapter
@@ -26,15 +28,17 @@ module ActiveModel
end
end
else
@hash = cached_object do
@hash[:data] = attributes_for_serializer(serializer, @options)
add_resource_links(@hash[:data], serializer)
@hash
end
@hash[:data] = attributes_for_serializer(serializer, @options)
add_resource_links(@hash[:data], serializer)
end
@hash
end
def fragment_cache(cached_hash, non_cached_hash)
root = false if @options.include?(:include)
JsonApi::FragmentCache.new().fragment_cache(root, cached_hash, non_cached_hash)
end
private
def add_links(resource, name, serializers)
@@ -43,7 +47,7 @@ module ActiveModel
resource[:links][name][:linkage] += serializers.map { |serializer| { type: serializer.type, id: serializer.id.to_s } }
end
def add_link(resource, name, serializer)
def add_link(resource, name, serializer, val=nil)
resource[:links] ||= {}
resource[:links][name] = { linkage: nil }
@@ -76,24 +80,27 @@ module ActiveModel
end
end
def attributes_for_serializer(serializer, options)
if serializer.respond_to?(:each)
result = []
serializer.each do |object|
options[:fields] = @fieldset && @fieldset.fields_for(serializer)
options[:required_fields] = [:id, :type]
attributes = object.attributes(options)
attributes[:id] = attributes[:id].to_s
result << attributes
result << cache_check(object) do
options[:required_fields] = [:id, :type]
attributes = object.attributes(options)
attributes[:id] = attributes[:id].to_s
result << attributes
end
end
else
options[:fields] = @fieldset && @fieldset.fields_for(serializer)
options[:required_fields] = [:id, :type]
result = serializer.attributes(options)
result[:id] = result[:id].to_s
result = cache_check(serializer) do
result = serializer.attributes(options)
result[:id] = result[:id].to_s
result
end
end
result
end
@@ -124,7 +131,11 @@ module ActiveModel
if association.respond_to?(:each)
add_links(attrs, name, association)
else
add_link(attrs, name, association)
if opts[:virtual_value]
add_link(attrs, name, nil, opts[:virtual_value])
else
add_link(attrs, name, association)
end
end
if options[:add_included]