2009-12-21 42 views
0

我正在編寫一個爲模型提供草稿的插件。刪除操作是一項可設計的操作,我並不總是希望在刪除發佈前刪除原點。所以我寫了自己的破壞方法來幫助解決這個問題。一切正常,除了我想要的東西除外,:before_destroy:after_destroy的自定義回調不再被觸發。我的自定義銷燬方法不會在銷燬回調之前和之後觸發默認值

如何任何想法:

  1. 重新綁定回調到我的破壞方法
  2. 工作一些alias_method_chain巫術
  3. 得到模型的列表回調,所以我可以給他們打電話手動
  4. 解決這個問題另一種方式

這裏是我破壞方法:

def destroy 
    if self.attribute_names.include?('draft') && self.skip_draft == false 
     if handle_destroy # if true is returned 
     super # go ahead and destroy as normal 
     end 
    else 
     super 
    end 
    end 

更新:我剛剛發現這個: correct way to override activerecordbasedestroy,但似乎所提出的技術不適應回調。有沒有辦法讓我的蛋糕也吃了呢?

回答

0

我錯了,當超級被調用時沒有被調用的回調。我最終依賴於最初發布的確切代碼。我改變了我的handle_destroy方法返回的方式

我會告訴你我是怎麼想出如何在想要顯式觸發回調的情況下觸發回調。

def destroy 
    if self.attribute_names.include?('draft') && self.skip_draft == false 
     if handle_destroy # if true is returned 
     super # go ahead and destroy as normal 
     else 
     # Execute all custom callbacks that are not dependent type callbacks (ie: if the callback method name contains "dependent") 
     # Dependent callbacks delete records and this is not what the drafting system is all about. 
     (self.class.before_destroy_callback_chain + self.class.after_destroy_callback_chain).each do |cb| 
      unless (cb.method.kind_of?(Symbol) && cb.method.to_s.match(/dependent/)) 
      cb.call(self) 
      end 
     end 
     end 
    else 
     # normal delete 
     super 
    end 
    end