active_model_serializers/lib/active_model/serializer/adapter.rb
Joao Moura 8a432ad2b3 Adding cache support to version 0.10.0
It's a new implementation of cache based on ActiveSupport::Cache.
The implementation abstracts the cache in Adapter class on a
private method called cached_object, this method is intended
to be used on Adapters inside serializable_hash method in order
to cache each instance of the object that will be returned by
the serializer.

Some of its features are:
- A different syntax. (no longer need the cache_key method).
- An options argument that have the same arguments of ActiveSupport::Cache::Store, plus a key option that will be the prefix of the object cache on a pattern "#{key}-#{object.id}".
- It cache the objects individually and not the whole Serializer return, re-using it in different requests (as a show and a index method for example.)
2015-02-02 14:53:34 -02:00

70 lines
1.6 KiB
Ruby

module ActiveModel
class Serializer
class Adapter
extend ActiveSupport::Autoload
autoload :Json
autoload :Null
autoload :JsonApi
attr_reader :serializer
def initialize(serializer, options = {})
@serializer = serializer
@options = options
end
def serializable_hash(options = {})
raise NotImplementedError, 'This is an abstract method. Should be implemented at the concrete adapter.'
end
def as_json(options = {})
hash = serializable_hash(options)
include_meta(hash)
end
def self.create(resource, options = {})
override = options.delete(:adapter)
klass = override ? adapter_class(override) : ActiveModel::Serializer.adapter
klass.new(resource, options)
end
def self.adapter_class(adapter)
"ActiveModel::Serializer::Adapter::#{adapter.to_s.classify}".safe_constantize
end
private
def meta
serializer.meta if serializer.respond_to?(:meta)
end
def meta_key
serializer.meta_key || "meta"
end
def root
serializer.json_key
end
def include_meta(json)
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