如何在清扫器中包含缓存过期的模块?

时间:2011-03-22 15:07:38

标签: ruby-on-rails caching observer-pattern sweeper

我们在rails应用程序中有以下清扫程序:

class AgencyEquipmentTypeSweeper < ActionController::Caching::Sweeper 
  observe AgencyEquipmentType

  #include ExpireOptions
  def after_update(agency_equipment_type)
    expire_options(agency_equipment_type)
  end

  def after_delete(agency_equipment_type)
    expire_options(agency_equipment_type)
  end

  def after_create(agency_equipment_type)
    expire_options(agency_equipment_type)
  end

  def expire_options(agency_equipment_type)
    Rails.cache.delete("agency_equipment_type_options/#{agency_equipment_type.agency_id}")
  end
end

我们想将after_update,after_delete和after_create回调提取到名为“ExpireOptions”的模块

模块应该看起来像这样(使用'expire_options'方法留在 原始清扫工):

module ExpireOptions
  def after_update(record)
    expire_options(record)
  end

  def after_delete(record)
    expire_options(record)
  end

  def after_create(record)
    expire_options(record)
  end
end

class AgencyEquipmentTypeSweeper < ActionController::Caching::Sweeper 
  observe AgencyEquipmentType

  include ExpireOptions

  def expire_options(agency_equipment_type)
    Rails.cache.delete("agency_equipment_type_options/#{agency_equipment_type.agency_id}")
  end
end

但是,如果我们在清扫器内明确定义方法,缓存过期才有效。有没有一种简单的方法可以将这些回调方法提取到模块中,并且仍然可以使用它们?

2 个答案:

答案 0 :(得分:2)

尝试:

module ExpireOptions
  def self.included(base)
    base.class_eval do
      after_update :custom_after_update
      after_delete :custom_after_delete
      after_create :custom_after_create
    end
  end

  def custom_after_update(record)
    expire_options(record)
  end

  def custom_after_delete(record)
    expire_options(record)
  end

  def custom_after_create(record)
    expire_options(record)
  end
end

答案 1 :(得分:0)

我会尝试类似的事情:

module ExpireOptions
  def after_update(record)
    self.send(:expire_options, record)
  end

  def after_delete(record)
    self.send(:expire_options, record)
  end

  def after_create(record)
    self.send(:expire_options, record)
  end
end

这应该确保它不会尝试在模块上调用这些方法,而是在self上调用,这有望成为调用对象。

这有帮助吗?

相关问题