我正在使用别名方法实现Rails模型回调(after_save,before_save)等。它只是将save
方法别名为save_with_callbacks
。它有效,但在定义before_save
或save
关键字抛出错误后必须调用alias
。我仍然在理解Rails回调是如何工作的,但是想知道是否有一种方法可以在模型中的任何地方使用before_filter。
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 :(得分:0)
我忘了用户一般不会定义'save'方法,但让ORM为你做。已将save
方法移至InstanceMethods
并解决了问题。