ccocchi / rabl-rails

Rails 4.2+ templating system with JSON, XML and Plist support.
MIT License
208 stars 51 forks source link

Is cache for templates using collection avail? #65

Closed blotto closed 8 years ago

blotto commented 9 years ago

The following

app/views/users/index.json.rabl

collection :@users cache extends "users/show"

will raise an error as such:

undefined method `cache_key' for #User::ActiveRecord_AssociationRelation:0x007fdee2c55350

Been trying a few variations with extends and partials, to no avail. Thanks for any suggestions!

blotto commented 9 years ago

btw i've been able to create cache_keys for collections using

 cache { |c| c.map(&:cache_key).join('/') }

its a nice way to cache the entire collection, but duplicates individual objects in the cache when another collection has one or more duplicate objects. Support of caching within partials/extends would allow for Russian Doll caching.

ccocchi commented 9 years ago

Russian doll caching is a bad idea when using rabl-rails, and I believe when rendering things like JSON or XML in any case.

The main reason with this idea is that you can't cache part of a JSON string and include it nicely in the middle of your response as you would do with HTML. So, if you can't cache the string the next best thing you can cache is the intermediate hash of your object rendered by the template. But then, having to call your cache instance (i.e. Memcached, redis, etc) would not be faster than generating the hash directly from the template. And the worst part is that you're trying to save time creating hashes where most time is spent transforming the hash into your formatted response (calling Oj::dump or hash.to_xml).

For theses reasons, partial caching is not part of this gem. When you're calling the cache method, you're stating that you want to cache the whole response, so that we can store the whole response body (as a string) in your cache instance.