Re: fragment caching and cache sweeping

I was wondering how to do this too, because the 2nd edition of Agile Web Development only mentions using Sweepers for action or page caching, not fragment. After experimenting with it, howver, I have verified that it does work.

For example sake lets say our app has a model called Post and you want to expire your cached fragment (probably a list of all posts) when a new post is created.

First, in your models directory, create a file named PostSweeper.rbNext, create a class inside this file called PostSweeper which inherits from ActionController::Caching::Sweeper and observes the model representing your posts, so

The parameter (post) is the ActiveRecord object that was just created, and is supplied automatically by the ActionController::Caching module.

The last thing you need to do is let the post controller know that it has a cache sweeper. Essentially it acts like a before_filter, matching method requests and calling the appropriate callback. So, in your PostController...

cache_sweeper :post_sweeper, :only => [:create]

This tells PostController that it only needs to register the callbacks for the create function.