Caching

Introduction

Cache Methods and Configuration


caches_page :public_action
expire_page :action => 'public_action'
caches_action :premium_content
caches_action :premium_content, :layout => false # don't cache the layout
expire_action :action => 'premium_content', :id => 2
cache 'recent_products'
expire_fragment 'recent_products'

# Configuration:
config.action_controller.perform_caching = true

Cache Storage

Cache Sweepers


class ArticleSweeper < ActionController::Caching::Sweeper
  observe Article
  def after_create(article) 
    expire_page(:controller => "content", :action => 'public_content') 
  end 
  def after_update(article)
    expire_action(:controller => "content",  :action => "premium_content", :id => article_id) 
  end 
  def after_destroy(article) 
    ...
  end 
end

Hooking up the Cache Sweeper


class ContentController < ApplicationController 
  cache_sweeper :article_sweeper, :only => [ :create_article, :update_article, :delete_article ]
end

Fragment Caching

Fragment Cache Storage


ActionController::Base.cache_store = :memory_store
ActionController::Base.cache_store = :file_store, "/path/to/cache/directory" 
ActionController::Base.cache_store = :drb_store, "druby://localhost:9192" 
ActionController::Base.cache_store = :mem_cache_store, "localhost" 
ActionController::Base.cache_store = MyOwnStore.new("parameter")

Conditional Gets – ETags


def show
  @article = Article.find(params[:id])
  response.last_modified = @article.published_at.utc
  response.etag = @article

  if request.fresh?(response)
    head :not_modified
  else
    respond_to do |wants|
      # normal response processing
    end
  end
end