Is it possible to cache active model serializers with an expiration timer?
I saw this article Fast JSON APIs in Rails with Key-Based Caches and ActiveModel::Serializers but I want to cache an object for only 10 minutes.
Is it possible to cache active model serializers with an expiration timer?
I saw this article Fast JSON APIs in Rails with Key-Based Caches and ActiveModel::Serializers but I want to cache an object for only 10 minutes.
Nicolo,
Newer versions of ActiveModel::Serializers actually remove caching, but it sounds like it’s planned for an upcoming release: https://www.pivotaltracker.com/s/projects/978898
Rails.cache
supports time-based expiration, so that may be the best route to explore for now.
Regarding the timer itself, any reason for expiring based on time and not cache key based expiration (Russian doll caching)?
I’m using AMS 0.8.2 (the old version).
I think for part of my request that the russian doll caching might work. How well does that work with objects that are using options? Is it smart enough to cache the right version of it based on different options?
As for the main request I want to cache via timer because there frequent enough updates to the objects within it that it would lose a lot of the performance boost of caching. The updates being made to the sub-objects do not need to be reflected immediately.
In case anyone comes across this, I found the answers to my own questions.
For caching options. You need to specify a different cache_key for each option.
Here is the serializer I did this for
class SlotSerializer < ActiveModel::Serializer
cached
attributes :id, :name, :color, :accepted_position_ids
def include_accepted_position_ids?
options[:draft_list]
end
def cache_key
if options[:draft_list]
object.cache_key + '/with_accepted_position_ids'
else
object.cache_key
end
end
Also here is how I cached the full request:
In the controller
json = cache("draft_list_#{@draft_list.time_window_id}", expires_in: 10.minutes) do
render_to_string json: @draft_list, draft_list: true
end
render json: json