Caching Techniques that Rails provides by Default

This is an introduction to the three types of caching techniques that Rails provides by default without the use of any third party plug-ins.

  • Page Caching
  • Action Caching
  • Fragment Caching
Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the web-server (i.e. Apache or nginx), without ever having to go through the Rails stack at all.

Page caching is an efficient way to cache stateless content.


Obviously, this is super-fast. Unfortunately, it can’t be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.

class ProductsController < ActionController
 
  caches_page :index
 
  def index
    @products = Products.all
  end
 
  def create
    expire_page :action => :index
  end
 
end
 
 
One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served.

This allows authentication and other restriction to be run while still serving the result of the output from a cached copy.
Clearing the cache works in the exact same way as with Page Caching.

class ProductsController < ActionController
 
  before_filter :authenticate
  caches_action :index
 
  def index
    @products = Product.all
  end
 
  def create
    expire_action :action => :index
  end
 
end
 
Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.

Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.

For the block of code , you can use fragment caching like here in the example we are caching the list of products.

<% cache('all_available_products') do %>
  All available products:
<% end %>
 
This fragment is then available to all actions in the ProductsController using the key and can be expired the same way:
expire_fragment('all_available_products')

Comments

Popular posts from this blog

Interview Question on Ruby on Rails

Inserting and Moving elements inside Ruby Array