ruby-on-rails – 如何在清扫器中包含缓存过期的模块?

我们在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

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

最佳答案 试试:

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
点赞