Skip to content

Instantly share code, notes, and snippets.

@bf4
Created December 24, 2012 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bf4/4370166 to your computer and use it in GitHub Desktop.
Save bf4/4370166 to your computer and use it in GitHub Desktop.
Two ways of clearing the cache in rails... needs work
module UserCache
def self.expire_cache(id)
@base ||= ActionController::Base.new
fragments = [ "user_#{id}", "mini_user_#{id}",
"admin_user_#{id}", "admin_mini_user_#{id}",
"admin_video_user_#{id}", "video_user_#{id}",
"archive_column", "archive",
"admin_archive_column", "admin_archive",
"embedded_video_#{id}"]
fragments.each do |fragment|
@base.expire_fragment(fragment)
end
end
end
require 'lib/user_cache'
class User < ActiveRecord::Base
after_save :expire_cache
after_destroy :expire_cache
# callback method #1
def expire_cache
UserCache.expire_cache(id)
end
end
-content_for :column do
-cache("#{prepend_if_admin?}archive_column") do
some content
-cache("#{prepend_if_admin?}archive") do
Some other content
module UserHelper
def prepend_if_admin?
(current_user && current_user.is_admin?) ? 'admin_' : ''
end
end
- cache('user_index_page') do
- users.each do |user|
- cache(user) do
= "some stuff about #{user.name}"
# Sweeper / Observer callback method #2
class UserSweeper < ActionController::Caching::Sweeper
observe User # This sweeper is going to keep an eye on the User model
# If our sweeper detects that a User was created call this
def after_create(user)
expire_cache_for(user)
end
# If our sweeper detects that a User was updated call this
def after_update(user)
expire_cache_for(user)
end
# If our sweeper detects that a User was deleted call this
def after_destroy(user)
expire_cache_for(user)
end
private
def expire_cache_for(user)
# Expire the index page now that we added a new user
# expire_page(:controller => 'users', :action => 'index')
expire_action(:controller => 'users', :action => 'index')
expire_action(:controller => 'users', :action => 'show', :id => user.id)
# Expire a fragment
expire_fragment('user_index_page')
rescue => e
Rails.logger.warn "DEBUGGING SWEEPER FAILURE: user #{user && user.respond_to?(:id) && user.id}: #{e.class}\t#{e.message}\t#{e.backtrace[0..4].join("\n\t")}"
end
end
class UsersController < ApplicationController
caches_action :index
cache_sweeper :user_sweeper
def index
end
def archive
unless fragment_exist?("archive") and fragment_exist?("archive_column")
# set some instance variables
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment