4

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

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

4

2 回答 2

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
于 2011-05-29T07:00:25.493 回答
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希望是调用对象。

这有帮助吗?

于 2011-05-31T14:06:26.873 回答