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