回调堆栈中的Rails around_action

时间:2016-03-21 22:45:24

标签: ruby-on-rails

我刚刚发现了around_action回调。我真的不明白这些回调如何与其余回调一起工作,特别是与使用(append_)before_actionprepend_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

还是别的什么?

1 个答案:

答案 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