← Back to Upcase

Caching with Active Model Serializers with a timer


(Nicolo) #1

Is it possible to cache active model serializers with an expiration timer?

I saw this article http://robots.thoughtbot.com/fast-json-apis-in-rails-with-key-based-caches-and but I want to cache an object for only 10 minutes.


(Joshua Clayton) #2

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)?


(Nicolo) #3

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.


(Nicolo) #4

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