Tell
Rails to use
memcached. In production.rb (or staging.rb or...)
ActionController::Base.cache_store = :mem_cache_store, "ip_address_of_memcached_server",
{:namespace => "my_super_app"}
Specify the action you want to cache.
class PostsController < ApplicationController
cache_action :posts_with_comments
def posts_with_comments
# shows all posts with comments
end
end
Create a sweeper. (app/sweepers/post_comment_sweeper.rb)
class PostCommentSweeper < ActionController::Caching::Sweeper
observe Post, Comment
def after_save(rec)
expire_cache_for(rec)
end
def after_destroy(rec)
expire_cache_for(rec)
end
private
def expire_cache_for(rec)
expire_action(:controller => '/posts', :action => 'posts_with_comments')
end
end
Note: the '/' in the controller name is important if you will invoke the sweeper from a nested controller. Without the '/' the cache_key will be wrong and rails will not find your data in the cache.
In each controller where we want our sweeper to be invoked if a observed model is saved or destroyed add the following line.
cache_sweeper :post_comment_sweeper
Now our cached action will be expired everytime a Post or a Comment is saved or destroyed.
BUT: this will only happen if the save or destroy is called from within one of the controllers we added the
cache_sweeper to.
The Sweeper will NOT be invoked if you do something like
Post.last.save in script/console.
I dont know why it's implemented that way but that's how it is.
Now fire up your memcached instance and you're set!