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