mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
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:
@@ -1,3 +1,5 @@
|
||||
require 'active_model/serializer/adapter/fragment_cache'
|
||||
|
||||
module ActiveModel
|
||||
class Serializer
|
||||
class Adapter
|
||||
@@ -32,8 +34,38 @@ module ActiveModel
|
||||
"ActiveModel::Serializer::Adapter::#{adapter.to_s.classify}".safe_constantize
|
||||
end
|
||||
|
||||
def fragment_cache(*args)
|
||||
raise NotImplementedError, 'This is an abstract method. Should be implemented at the concrete adapter.'
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def cache_check(serializer)
|
||||
@cached_serializer = serializer
|
||||
@klass = @cached_serializer.class
|
||||
if is_cached?
|
||||
@klass._cache.fetch(cache_key, @klass._cache_options) do
|
||||
yield
|
||||
end
|
||||
elsif is_fragment_cached?
|
||||
FragmentCache.new(self, @cached_serializer, @options, @root).fetch
|
||||
else
|
||||
yield
|
||||
end
|
||||
end
|
||||
|
||||
def is_cached?
|
||||
@klass._cache && !@klass._cache_only && !@klass._cache_except
|
||||
end
|
||||
|
||||
def is_fragment_cached?
|
||||
@klass._cache_only && !@klass._cache_except || !@klass._cache_only && @klass._cache_except
|
||||
end
|
||||
|
||||
def cache_key
|
||||
(@klass._cache_key) ? "#{@klass._cache_key}/#{@cached_serializer.object.id}-#{@cached_serializer.object.updated_at}" : @cached_serializer.object.cache_key
|
||||
end
|
||||
|
||||
def meta
|
||||
serializer.meta if serializer.respond_to?(:meta)
|
||||
end
|
||||
@@ -50,20 +82,6 @@ module ActiveModel
|
||||
json[meta_key] = meta if meta && root
|
||||
json
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def cached_object
|
||||
klass = serializer.class
|
||||
if klass._cache
|
||||
_cache_key = (klass._cache_key) ? "#{klass._cache_key}/#{serializer.object.id}-#{serializer.object.updated_at}" : serializer.object.cache_key
|
||||
klass._cache.fetch(_cache_key, klass._cache_options) do
|
||||
yield
|
||||
end
|
||||
else
|
||||
yield
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user