How to enable a cache expiration module in sweepers?

The rails app has the following sweeper:

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 would like to extract the after_update, after_delete and after_create callbacks into a module called "ExpireOptions"

The module should look like this (using the 'expire_options' method remaining 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, cache expiration works only if we define methods explicitly in the sweeper. Is there an easy way to extract these callback methods into a module and still work with them?

+4
source share
2 answers

Try:

 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 
+2
source

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 that he is not trying to call these methods in the module, but on self , which we hope will be the caller.

Does it help?

0
source

Source: https://habr.com/ru/post/1344785/


All Articles