Caching in RABL

Brian edited this page Feb 18, 2014 · 6 revisions

Caching works by saving the entire template output to the configured cache_store in your application. Note that caching is currently only available for Rails but support for other frameworks is planned in a future release.

For Rails, requires action_controller.perform_caching to be set to true in your environment, and for cache to be set to a key (object that responds to cache_key method, array or string).

# app/views/users/show.json.rabl
object @quiz
cache @quiz # key = rabl/quiz/[cache_key]
attribute :title

The cache keyword accepts the same parameters as fragment caching for Rails.

cache @user            # calls @user.cache_key
cache ['kewl', @user]  # calls @user.cache_key and prefixes with kewl/
cache 'lists'          # explicit key of 'lists'
cache 'lists', expires_in: 1.hour

The cache keyword can be used from within the base template or any extended template including partials.

# app/views/users/index.json.rabl
collection @users
cache @users  # key = rabl/users/[cache_key]/users/[cache_key]/...

extends "users/show"

And within the extended template:

# app/views/users/show.json.rabl
object @user
cache @user  # key = rabl/user/[cache_key]/...

attributes :name, :email

Another example of extending your object templates.

# app/views/users/show.json.rabl
object @user

extends "users/user"
# app/views/users/user.json.rabl
cache  # key = rabl/user/[cache_key]/...

attributes :name, :email

If you need to reference the root object from an extended view, you can use root_object from your templates:

# app/views/users/show.rabl
object @task
extends 'users/base'
# app/views/users/base.rabl
cache ["base", root_object]

attributes :name, :email

Caching can significantly speed up the rendering of RABL templates in production and is strongly recommended when possible.

You can define your own caching engine by creating an object that responds to fetch(key, cache_options, &block) and setting the configuration option (see the default engine)

   config.cache_engine = SuperAdvancedCacheEngine.new