Referenced Page Caching
Referenced Page Caching is a small wrapper around Rails’ page caching. It allows you to add references to a current page’s cache file. These references are then used to expire all the pages that are referenced when it is modified or destroyed.
=== The Cached Page model
The Cached Page model stores the cached page urls and the references. The ‘reference’ string is made by joining the ID and class name of a reference:
1:Post, 3:Comment, etc
Here’s a sample table schema:
create_table :cached_pages, :force => true do |t|
t.column :url, :string, :limit => 255
t.column :references, :text
t.column :updated_at, :datetime
end
Run the cached page migration generator to create one:
./script/generate cached_page_migration
=== Caboose::Caching::ReferencedCachingSystem
This module is added to ActionController::Base automatically. Here’s an example of using it:
class PostController < ApplicationController
after_filter :add_post_references, :only => :index
caches_page_with_references :list
end
def list
@posts = Post.find :all
end
protected
def add_post_references
self.cached_references += @posts
end
=== Expiring pages
Ah, the fun part of any caching system. First, generate a sweeper:
./script/generate referenced_cache_sweeper reference
Add the sweeper to your controller:
class PostController < ApplicationController
cache_sweeper :reference_sweeper, :only => [:create, :update, :destroy]
end
def create
@post = Post.create(params[:post])
end
Be sure to modify the sweeper for any special rules in your application.
=== The Cache Manager
After that, visit /referenced_page_caching in your application to manage and sweep the cache.
It’s understandable that you may want to require authentication. Add this to your config/environments/production.rb:
- config/environments/production.rb config.after_initialize do require ‘application’ unless Object.const_defined?(:ApplicationController) ReferencedPageCachingController.class_eval do # The controller is disabled by default self.enabled = true before_filter :login_required protected # only allow admins # this obviously depends on how your auth system works def authorized? current_user.is_a?(Admin) end end end
The exact code of course depends on the specific needs of your application.
=== CREDITS
Rick Olson – model/controller code Josh Goebel – design
Good luck!