mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
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.)
37 lines
1.1 KiB
Ruby
37 lines
1.1 KiB
Ruby
module ActiveModel
|
|
class Serializer
|
|
class Adapter
|
|
class Json < Adapter
|
|
def serializable_hash(options = {})
|
|
if serializer.respond_to?(:each)
|
|
@result = serializer.map{|s| self.class.new(s).serializable_hash }
|
|
else
|
|
@result = cached_object do
|
|
@hash = serializer.attributes(options)
|
|
serializer.each_association do |name, association, opts|
|
|
if association.respond_to?(:each)
|
|
array_serializer = association
|
|
@hash[name] = array_serializer.map { |item| item.attributes(opts) }
|
|
else
|
|
if association
|
|
@hash[name] = association.attributes(options)
|
|
else
|
|
@hash[name] = nil
|
|
end
|
|
end
|
|
end
|
|
@hash
|
|
end
|
|
end
|
|
|
|
if root = options.fetch(:root, serializer.json_key)
|
|
@result = { root => @result }
|
|
end
|
|
|
|
@result
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|