Rails Cache Sweeper

I am trying to implement a Cache Sweeper that will filter a specific controller action.

class ProductsController < ActionController caches_action :index cache_sweeper :product_sweeper def index @products = Product.all end def update_some_state #... do some stuff which doesn't trigger a product save, but invalidates cache end end 

Sweeper Class:

 class ProductSweeper < ActionController::Caching::Sweeper observe Product #expire fragment after model update def after_save expire_fragment('all_available_products') end #expire different cache after controller method modifying state is called. def after_update_some_state expire_action(:controller => 'products', :action => 'index') end end 

The after_save callback ActiveRecord will work fine, but the callback on the after_update_some_state controller actions never seems to be called.

+4
source share
2 answers

It seems like I just missed the name of the controller when trying to get callbacks for controller actions. My sweeper should be:

 class ProductSweeper < ActionController::Caching::Sweeper observe Product #expire fragment after model update def after_save expire_fragment('all_available_products') end #expire different cache after controller method modifying state is called. def after_products_update_some_state expire_action(:controller => 'products', :action => 'index') end #can also use before: def before_products_update_some_state #do something before. end end 
+4
source

I think your sweeper should look like this:

 class ProductSweeper < ActionController::Caching::Sweeper observe Product def after_save(product) expire_cache(product) end def after_destroy(product) expire_cache(product) end private def expire_cache(product) expire_fragment('all_available_products') expire_page(:controller => 'products', :action => 'index') end 

after_index not a callback unless you define it.

In the controller, you must specify the actions in which the sweeper should be started, in rest order, these actions should be create, update, destroy , so your controller declaration should look like this:

 class ProductsController < ActionController caches_action :index cache_sweeper :product_sweeper, :only => [:create, :update, :destroy] def index @products = Product.all end def create @product = Product.new(params[:product]) if @product.save # triggers the sweeper. # do something else # do something else end end # update and stuff ... end 

Hope this helps you!

+3
source

All Articles