2011-03-22 53 views
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 

但緩存expirati如果我們在清理程序中明確定義方法,ons纔會起作用。有沒有簡單的方法來提取這些回調方法到一個模塊,並仍然有它們的工作?

+1

這很奇怪。這兩個例子都適用於本地。你用什麼來做你的緩存存儲? – 2011-05-25 07:08:16

+1

它應該與您當前的代碼一起工作。無需更改。包括聲明照顧一切。 – Anand 2011-05-27 10:12:20

+0

基於模塊的方法after_create等被調用嗎? – moritz 2011-05-31 17:56:46

回答

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

我收到了:'included':未定義的方法'after_update'for AgencyEquipmentTypeSweeper:類 – btelles 2011-06-02 13:18:57

+0

您正在使用哪個版本的Ror? – 2011-06-02 19:53:38

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這將有望成爲調用對象。

這有幫助嗎?

+0

看起來像原始代碼工作...無賴。 – btelles 2011-06-02 13:32:14