Cache Your Rails App
-
Upload
achmad-gozali -
Category
Technology
-
view
1.171 -
download
0
Transcript of Cache Your Rails App
Content Caching in Rails
Ahmad [email protected]
Content Cache
• Page cache• Action cache• Fragment cache
Page Cache (1)
• Easiest to use• Fastest• Worst scaling properties
Page Cache (2)
• Pages created by Rails as normal• Written out to public directory• Cached pages served directly by webserver without involking rails
Enable Page Caching
class PostsController < ApplicationController caches_page :show cache_sweeper :posts_sweeper, :only => [:create, :update, :destroy]
def show Post.find_by_id(params[:id]) end
end
Sweepers
Rails::Initializer.run do |config| # ... config.load_paths += %W( #{RAILS_ROOT}/app/sweepers ) # ...end
Expires Cache
class PostsSweeper < ActionController::Caching::Sweeper observe Post def after_update(post) expire_cache_for(post) end ...
.htaccess
RewriteRule ^$ index.html [QSA]RewriteRule ^([^.]+)$ $1.html [QSA]RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
Action Caching
• Similar to page cache, but runs entirely inside of Rails• Slower, because Rails is always involved• Much less complex on the web server side; no mod_rewrite tricks• Uses the fragment cache internally
Example
class PostsController < ApplicationController layout 'base' before_filter :authenticate caches_action :list, :show
Cleanup Action Cache
expire_action(:controller => 'posts', :action => 'list') expire_action(:controller => 'posts', :action => 'show', :id => record.id)
Fragment Cache
• You have to call it yourself, because it works on short bits of data, not whole pages.• read_fragment(key) and write_fragment(key,value)• Expire with expire_fragment(key) (or regex).• No way to list entries.
Example<strong>My Blog Posts</strong><% cache do %> <ul> <% for post in @posts %> <li><%= link_to post.title, :controller => 'posts', :action => 'show', :id => post %></li> <% end %> </ul><% end %>
Post Controllers
def list unless read_fragment({}) @post = Post.find(:all, :order => 'created_on desc', :limit => 10) %> endend
Expire Fragment Cache
expire_fragment(:controller => 'post', :action => 'list')
Demo