Russian doll caching.

Page and action caching are extracted to a separate gem. Page and action caching requires too much manual intervention (manually expiring caches when the underlying model objects are updated). Instead, use Russian doll caching.

So what’s this Russian doll caching all about?

Lets take an example of e-commerce application.
On the store page we display a list of products and we don’t want to render the products again and again every time user refresh the page.
Thinking about it, we only need to re-render things if a product changed, and even then we need to render only the products
that actually changed.

So how we can do that ?
The first thing we’re going to do is to modify the configuration for the development environment to turn on caching.

config.action_controller.perform_caching = true

As with all configuration changes, you need to restart your server.

Focusing on the first part of the problem, we need to add code that returns the most recently updated product.

class Product < ActiveRecord::Base

def self.latest
Product.order(:updated_at).last
end
end

Next we mark the sections of our template that we need to update if any product changes, and inside that section we mark the subsection that we need in order to update any specific product that changed.


➤ cache ['store', Product.latest] do
@products.each do |product|
➤ cache ['entry', product] do

image_tag(product.image_url)

= sanitize(product.description)

= number_to_currency(product.price)

end
➤ end
➤end

In addition to bracketing the sections, we identify the components of the name
for each cache entry. We make the choice to call the overall cache entry store
and the individual cache entries entry. We also associate a product with each,
namely, the latest with the overall store and the individual product we are
rendering with the entry.
Bracketed sections can be nested to arbitrary depth, which is why those in
the Rails community have come to refer to this as Russian doll caching.4
With this, we’re done! Rails takes care of all of the rest, including managing
the storage and deciding when to invalidate old entries. If you’re really interested,
there are all sorts of knobs you can turn and choices as to what
backing store to use for the cache. It’s nothing you need to worry about now,
but it might be worth bookmarking the overview page of Caching with Rails
in the RailsGuides.

Advertisements