Other Systems | 181
class PersonSweeper < ActionController::Caching::Sweeper
observe Person
def after_save(record)
expire_cache(record)
end
def after_destroy(record)
expire_cache(record)
end
def expire_cache(record)
# Actions to take when +record+ is changed or destroyed
expire_page :controller => 'person', :action => 'show', :id => record.id
expire_page :controller => 'person', :action => 'list'
end
end
The sweeper must be activated by name from the controller:
class PersonController < ApplicationController
caches_page :list, :show, :new
cache_sweeper :person_sweeper, :only => [ :create, :update, :destroy ]
end
Because sweepers bridge between the model and controller, it makes sense to create
a new directory for the caching-related classes. Place the sweeper inapp/cachers, and
add the following line to yourenvironment.rb file:*
config.load_paths += %W(#{RAILS_ROOT}/app/cachers)
As long as your files are named according to standard Rails conventions (Person-
Sweeper is defined inperson_sweeper.rb), Rails will autoload the corresponding file
when an unknown symbol such as PersonSweeper is first encountered. Theload_paths
option simply adds to the list of locations thatDependenciessearches. We covered
Dependencies in detail in Chapter 2.
Other Systems
The remainder of this chapter is a collection of miscellaneous performance tips and
solutions to common problems. If you have specific trouble, the Rails wiki (http://
wiki.rubyonrails.com/) might help. The wiki is disorganized at times, but it has a
large amount of relevant information on many topics if you are willing to search.
- The idea and implementation of this separation of concerns come from Mephisto, which is a good example
of a cleanly structured Rails application. The code is available fromhttp://svn.techno-weenie.net/projects/
mephisto/trunk/.