我刚刚发现了around_action回调。我真的不明白这些回调如何与其余回调一起工作,特别是与使用(append_)before_action
或prepend_before
回调相比,调用堆栈的外观如何。周围的动作回调是否适合这样的访问控制:
ApplicationController < ...
around_action :access_control
private
def access_control
if @authorized
yield
else
# Show error page
end
end
class AdminController < ApplicationController
before_action :authorize_admins
private
def authorize_admins
if current_user.admin?
@authorizez = true
end
end
around_action的行为是append_before_action
+ prepend_after_action
还是prepend_before_action
+ append_after_action
?
还是别的什么?
答案 0 :(得分:4)
around_action
更像append_before_action
+ prepend_after_action
。
在内部,请注意rails
有两个数组,@before_actions
和@after_actions
。因此,当您声明around_action
时,它会将其推送/追加到@before_actions
的末尾,并将其移至/ @after_actions
前。
快速测试如下:
class SomeController < ApplicationController
before_action :before_action
after_action :after_action
around_filter :around_action
def before_action
$stderr.puts "From before_action"
end
def after_action
$stderr.puts "From after_action"
end
def around_action
begin
$stderr.puts "From around_action before yielding"
yield
$stderr.puts "From around_action after yielding"
end
end
def index
end
end
我在日志中得到以下内容:
Started GET "/" for 127.0.0.1 at 2016-03-21 17:11:01 -0700
Processing by SomeController#index as HTML
From before_action
From around_action before yielding
Rendered some/index.html.slim within layouts/index (1.5ms)
From around_action after yielding
From after_action