Page caching is one of the most efficient forms of caching in Rails app
1.
enable perform_caching
development.rbconfig.action_controller.perform_caching = true
2.
add page caching to the actions we want to cache
3.class ProductsController < ApplicationControllercaches_page :index, :showdef index@products = Product.page(params[:page]).per_page(5)enddef show@product = Product.find(params[:id])end.....
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
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
5.cache expirationget 'products/page/:page', to: 'products#index'
when the content of the cache changes , we will need to flush the cache
6.Flash message is stored in the cache , so it's shown everytimeexpire_page products_path
expire_page product_path(product)
expire_page "/"
FileUtils.rm_rf "#{page_cache_directory}/products/page"
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 %>
沒有留言:
張貼留言