define_callbacks
set_callback
skip_callback
reset_callbacks
CALLBACK_FILTER_TYPES = [:before, :after, :around]
class Report
include ActiveSupport::Callbacks
# 定义一条回调链,名字是 print
define_callbacks :print
# 把类型为 before,名字为 before_print 的回调,放到 print 回调链里
set_callback :print, :before, :before_print
# 把类型为 after,名字为 after_print 的回调,放到 print 回调链里
set_callback :print, :after, :after_print
def print_me
# 在执行"真正要执行的代码"的前后,执行 print 回调链里的回调
run_callbacks :print do
# 真正要执行的代码
p 'print me'
end
end
# 以下两方法已经放入 print 回调链,所以会被调用。
def before_print
p 'before print'
end
def after_print
p 'after print'
end
end
Report.new.print_me
# => "before print"
# => "print me"
# => "after print"