2014年4月1日 星期二

Page Caching - rails 3

Source : http://railscasts.com/episodes/89-page-caching-revised?view=asciicast

Page caching is one of the most efficient forms of caching  in Rails app

1.
enable perform_caching

development.rb
config.action_controller.perform_caching = true

2.
add page caching to the actions we want to cache

class ProductsController < ApplicationController
  
  caches_page :index, :show
  
  def index
    @products = Product.page(params[:page]).per_page(5)
  end
  def show
    @product = Product.find(params[:id])
  end
.....
3.
then , refresh the page , we will find in the folder "public" , it auto create a file named "product.html" contains the full response for the /products page

4.
one issue we will have is that any URL parameters we pass are ignored .
so include the page as part of the URL path instead of as a query parameter

get 'products/page/:page', to: 'products#index'
5.cache expiration
when the content of the cache changes , we will need to flush the cache
    expire_page products_path
    expire_page product_path(product)
    expire_page "/"
    FileUtils.rm_rf "#{page_cache_directory}/products/page"
6.Flash message is stored in the cache , so it's shown everytime
   we need a way to hide these when we're caching the page
  before_filter(only: [:index, :show]) { @page_caching = true }  
<%= csrf_meta_tag unless @page_caching %>
<% unless @page_caching %>
                <% flash.each do |name, msg| %>
            <%= content_tag :div, msg, id: "flash_#{name}" %>
          <% end %>


沒有留言:

張貼留言