Manually Invoking a Rails Sweeper

February 02, 2009

Let’s say you have a Rails app, and that app has a Photo model, and that photo model has many Destinations, and the destination pages are cached to disk, and when you update a photo you need to expire all of the destination pages that photo is associated with.

By default Rails won’t do this using Sweepers as it only affects the object itself after saving it and once you’ve reached that point the old associated relationships are lost.

Rails doesn’t track the changes made to associations like it does model attributes. There isn’t a photo.destinations_was. To get around this you can call the sweeper manually before updating it—when the photo still knows about it’s current destinations. In your controller, before calling @photo.update_attributes(....) do this:

PhotoSweeper.instance.expire_photo(@photo)

This assumes of course that expire_photo(photo) is a method of the PhotoSweeper class. That method can then iterate through the existing destinations it’s associated with and expire them.