2011-08-21 22 views
0

我正在玩着使用別名方法實現Rails模型回調(after_save,before_save)等。它所做的只是將save方法別名爲save_with_callbacks。它的工作原理除before_save必須在save被定義或alias關鍵字引發錯誤後調用。我仍然在理解Rails回調是如何工作的,但是想知道是否有方法在模型中的任何地方使用before_filter。使用'alias'關鍵字實現Rails回調

module ClassMethods 
    def before_save 
    class_eval do 
     # old_save points to save 
     # save points to save_with_callbacks 
     alias :old_save :save 
     alias :save :save_with_callbacks 
    end 
    end 
end 

module InstanceMethods 
    def save_with_callbacks 
    @save_with_callbacks_text = 'Saving with callbacks' 
    old_save 
    end 
end 

class Task 
    extend ClassMethods 
    include InstanceMethods 

    attr_reader :save_text, :save_with_callbacks_text 

    def save 
    @save_text = 'Saving' 
    end 

    # Needs to be called after save, save_with_callbacks are defined 
    before_save 
end 

回答

0

我忘了用戶通常不定義'save'方法,但讓ORM爲你做。將save方法移至InstanceMethods並解決了該問題。