rocket_pants icon indicating copy to clipboard operation
rocket_pants copied to clipboard

Caching collections with etags

Open manuelmeurer opened this issue 11 years ago • 3 comments

Right now RocketPants only supports caching collections using "expires in". I would like to add the option to cache collections with etags. There have been several approaches:

  • http://www.saturnflyer.com/blog/jim/2009/10/27/cache-key-for-collections-in-activerecord/
  • http://stackoverflow.com/questions/15194270/rails-cache-key-generated-as-activerecordrelation
  • https://rails.lighthouseapp.com/projects/8994/tickets/5731-arrelationcache_key

I am testing this right now by calling

cache_response collection, true if RocketPants.caching_enabled?

in my controller (I am using Rabl instead of Active Record Serializers, so I don't use exposes). As you see, I am passing my collection and indicate that it's a singular resource, thus triggering the etag caching. Then I use the following to monkeypatch ActiveRecord::Relation to expose a cache_key and rp_object_key:

# config/initializers/ar_relation_cache_key.rb
ActiveRecord::Relation.class_eval do
  def cache_key
    parts = [self.to_sql]
    if self.any?
      parts.concat [
        self.count,
        self.pluck(:id).join('-'),
        self.maximum(:updated_at).to_s(:number),
        self.maximum(:created_at).to_s(:number)
      ]
    end
    parts.join('/')
  end

  def rp_object_key
    self.to_sql
  end
end

Would you be open to adding an option where RocketPants would check the collection for a cache_key, use etag caching if it has one and "expires in" if not?

manuelmeurer avatar Feb 16 '14 14:02 manuelmeurer

Definitely open to it, but I don't have time to work on it - would you perhaps be interested in implementing it and sending a PR?

Sutto avatar Feb 25 '14 11:02 Sutto

Sure, I will work on it soon!

manuelmeurer avatar Feb 28 '14 15:02 manuelmeurer

Cheers!

Sutto avatar Mar 02 '14 00:03 Sutto