Topic: fragment caching and cache sweeping

i've setup fragment caching one one particularly slow part of our app.
i am currently using :file_store, "/fragment_cache"

but I will likely change that to :mem_cache_store if i can figure out how to do that on our (mt) Grid-Server.

in my "wall" view.
[code = ruby]
<% cache do %>
     <%= render :partial => 'increment', :collection => @incrementindex %>   
<% end %>
[/code]

i've read a little about cache sweeping, but didnt really grasp how it works.

how would i set up a sweeper for that fragment?

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.rb
Next, create a class inside this file called PostSweeper which inherits from ActionController::Caching::Sweeper and observes the model representing your posts, so

class PostSweeper < ActionController::Caching::Sweeper
  observe Post

then just define your callbacks
def after_create(post)
  logger.info("Expiring cached post index fragment")
  expire_fragment(:controller => 'posts', :action => :index)
end

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.

Thats all there is to it.  Pretty snazzy, eh?

Re: fragment caching and cache sweeping

hey thanks for your help, im going to try and get it working in a bit.