views:

193

answers:

3

How to expire a directory in Rails?

I have a blog where /posts/ lists all the posts. Controller posts, action index. Pretty standard stuff.

Posts are paginated in groups of 10 using will_paginate.

The pages are being cached like this:

/posts/
/posts/index/2
/posts/index/3
/posts/index/4
...
/posts/index/134
/posts/index/135
... 
etc..

When I need to expire this pages, expire_page(posts_path) won't do the job, it will only expire /posts.html.

What's the best way to expire the paginated pages? Since there is an undetermined number of pages, should I just expire the whole /posts/index/ directory? How can I expire a directory?

thanks

A: 

You can pass a Regexp to expire_fragment:

expire_fragment(r%{/posts/index/\d+})

But be warned that only works when your cache store is capable of iterating over all keys. For example, it doesn't work with memcached.

Edit: I see this is page caching, not fragment caching. It seems expire_page does not accept a Regexp. Hmm.

ScottJ
A: 

Sounds like you want a sweeper to run when you need to expire those pages. Check out this Rails Envy post http://railsenvy.com/2007/02/28/rails-caching-tutorial#sweepers

If you can't remove your pages with some set of hash params, then there is an example of removing an entire directory of cached files at http://railsenvy.com/2007/02/28/rails-caching-tutorial#clearing

There might be some more info in that article that could help you, it is a really good 2 part explanation of all Rails caching.

danivovich
+2  A: 

You're doing page caching, right? Why not just delete the directory?

system("rm -rf #{RAILS_ROOT}/public/posts")
#Or, in more Rubyish code
FileUtils.rm_rf "#{RAILS_ROOT}/public/posts"
Patrick McKenzie
I ended up doing something very similar to your answer, it pointed me to the right direction, thank you. I found out page caching can turn into a nightmare if you have a lot of controllers and sweepers.
deb