How does one include a module with cache expirations in sweepers?
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_creat开发者_JS百科e 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?
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
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?
精彩评论