mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 15:23:06 +00:00
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.)
This commit is contained in:
13
test/fixtures/poro.rb
vendored
13
test/fixtures/poro.rb
vendored
@@ -3,6 +3,14 @@ class Model
|
||||
@attributes = hash
|
||||
end
|
||||
|
||||
def cache_key
|
||||
"#{self.class.name.downcase}/#{self.id}-#{self.updated_at}"
|
||||
end
|
||||
|
||||
def updated_at
|
||||
@attributes[:updated_at] ||= DateTime.now.to_time.to_i
|
||||
end
|
||||
|
||||
def read_attribute_for_serialization(name)
|
||||
if name == :id || name == 'id'
|
||||
id
|
||||
@@ -55,7 +63,8 @@ module Spam; end
|
||||
Spam::UnrelatedLink = Class.new(Model)
|
||||
|
||||
PostSerializer = Class.new(ActiveModel::Serializer) do
|
||||
attributes :title, :body, :id
|
||||
cache key:'post', expires_in: 0.05
|
||||
attributes :id, :title, :body
|
||||
|
||||
has_many :comments
|
||||
belongs_to :blog
|
||||
@@ -77,6 +86,7 @@ SpammyPostSerializer = Class.new(ActiveModel::Serializer) do
|
||||
end
|
||||
|
||||
CommentSerializer = Class.new(ActiveModel::Serializer) do
|
||||
cache expires_in: 1.day
|
||||
attributes :id, :body
|
||||
|
||||
belongs_to :post
|
||||
@@ -84,6 +94,7 @@ CommentSerializer = Class.new(ActiveModel::Serializer) do
|
||||
end
|
||||
|
||||
AuthorSerializer = Class.new(ActiveModel::Serializer) do
|
||||
cache key:'writer'
|
||||
attributes :id, :name
|
||||
|
||||
has_many :posts, embed: :ids
|
||||
|
||||
Reference in New Issue
Block a user