How to call expire_fragment from Rails Observer/Model?

Marston A. picture Marston A. · Dec 26, 2008 · Viewed 13.6k times · Source

I've pretty much tried everything, but it seems impossible to use expire_fragment from models? I know you're not supposed to and it's non-MVC, but surely there much be some way to do it.

I created a module in lib/cache_helper.rb with all my expire helpers, within each are just a bunch of expire_fragment calls. I have all my cache sweepers setup under /app/sweepers and have an "include CacheHelper" in my application controller so expiring cache within the app when called via controllers works fine.

Then things is I have some external daemons and especially some recurring cron tasks which call a rake task that calls a certain method. This method does some processing and inputs entries into the model, after which I need to expire cache.

What's the best way to do this as I can't specify cache sweeper within the model. Straight up observers seem to be the best solution but then it complains about expire_fragment being undefined etc etc, I've even tried including the ActionController caching classes into the observer but that didn't work. I'd love some ideas of how to create a solution for this. Thanks.

Answer

Orion Edwards picture Orion Edwards · Feb 19, 2009

Disclaimer: My rails is a bit rusty, but this or something like it should work

ActionController::Base.new.expire_fragment(key, options = nil)