Rails Cache Sweeper

时间:2010-09-22 15:58:17

标签: ruby-on-rails caching

我正在尝试实现一个缓存清理程序,它将过滤特定的控制器操作。

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

ActiveRecord回调'after_save'可以正常工作,但控制器动作'after_update_some_state'上的回调似乎永远不会被调用。

2 个答案:

答案 0 :(得分:4)

在尝试获取控制器操作的回调时,看起来我只是错过了控制器名称。我的清扫工应该是:

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

答案 1 :(得分:3)

我认为你的清扫车应该是这样的:

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不是回调。

在控制器中,您应该指定应该触发清扫程序的那些操作,以一种安静的方式执行这些操作create, update, destroy,这样您的控制器声明应如下所示:

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 

我希望它可以帮到你!