How does one include a module with cache expirations in sweepers?

686 Views Asked by At

We have the following sweeper in a rails application:

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

We'd like to extract the after_update, after_delete, and after_create callbacks to a module called "ExpireOptions"

The module should look like this (with the 'expire_options' method staying behind in the original sweeper):

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

BUT the cache expirations only work if we define the methods explicitly inside the sweeper. Is there an easy way to extract those callback methods to a module, and still have them work?

2

There are 2 best solutions below

2
On

Try with:

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
0
On

I would try something like:

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

This should make sure it does not try to call those methods on the module, but on self which would hopefully be the calling object.

Does that help?