Skip to content

Instantly share code, notes, and snippets.

@hayeah
Last active August 29, 2015 13:57
Show Gist options
  • Save hayeah/9380257 to your computer and use it in GitHub Desktop.
Save hayeah/9380257 to your computer and use it in GitHub Desktop.
callback chain ordering
require "active_support/callbacks"
class Foo
include ActiveSupport::Callbacks
define_callbacks :foo
set_callback :foo, :around, :around_1
set_callback :foo, :before, :before_1
set_callback :foo, :after, :after_1
def after_1
puts "after_1"
end
def before_1
puts "before_1"
end
def before_2
puts "before_2"
end
def around_1
puts "around_1 top"
yield
puts "around_1 bottom"
end
end
foo = Foo.new
foo.run_callbacks :foo do
puts "in run callbacks"
end
@hayeah
Copy link
Author

hayeah commented Mar 6, 2014

The output is:

around_1 top
before_1
in run callbacks
after_1
around_1 bottom

ActiveSupport::Callback doesn't guarantee that all :before callbacks are called before :around callbacks. Also, the :after_1 callback is called before around_1 is finished.

@crabmc
Copy link

crabmc commented Mar 6, 2014

关于这一段:
ActiveSupport::Callback doesn't guarantee that all :before callbacks are called before :around callbacks. Also, the :after_1 callback is called before around_1 is finished.
是你的推断还是官方文档里写的?

据我写测试code来看,执行结果是可以保证的,取决于set_callback的顺序
https://github.com/crabmc/learn_ruby_from_zero/blob/master/active_support/callback_1.rb
这段代码我跑出的结果是固定的。主要是around搀和进去容易让人理不清头绪。

@hayeah
Copy link
Author

hayeah commented Mar 6, 2014

顺序是固定的,没错。我原本以为顺序应该是

before_1
  around_1 top
    un run callbacks
  around_1 bottom
after_1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment