简体   繁体   English

Railsaround_action在回调堆栈中

[英]Rails around_action in the callback stack

I just discovered around_action callbacks. 我刚刚发现了around_action回调。 I don't really understand how those callbacks work with the rest, and especially how the call stack looks like compared to using (append_)before_action or prepend_before callbacks. 我不太了解这些回调如何与其余回调一起使用,尤其是与使用(append_)before_actionprepend_before回调相比,调用堆栈的外观如何。 Would the around action callback be good for an access control like this : 周围动作回调对于这样的访问控制是否有用:

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

Does around_action behave like an append_before_action + prepend_after_action or prepend_before_action + append_after_action ? around_action的行为是否类似于append_before_action + prepend_after_actionprepend_before_action + append_after_action

Or something different ? 还是有所不同?

around_action are more like append_before_action + prepend_after_action . around_action更像append_before_action + prepend_after_action

Internally, think of it like rails has two arrays, @before_actions and @after_actions . 在内部,将其想像为rails有两个数组, @before_actions@after_actions So when you declare around_action , it pushes/appends it to the end of @before_actions and it unshift/prepends to the @after_actions . 因此,当您声明around_action ,它会将其推入/追加到@before_actions的末尾,并@before_actions /将其附加到@after_actions

With a quick test as follows: 进行如下快速测试:

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

I got the following in the log: 我在日志中得到以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM