gpt4 book ai didi

ruby-on-rails - around_action 回调如何工作?需要解释

转载 作者:行者123 更新时间:2023-12-03 11:48:47 28 4
gpt4 key购买 nike

我对 around_action 感到非常困惑。它们是如何工作的?有人可以向我提供他们如何工作的示例/解释吗?

这是我的敏捷 Web 开发 4 书中的引述:

Around callbacks wrap the execution of actions. You can write an around callback in two different styles. In the first, the callback is a single chunk of code. That code is called before the action is executed. If the callback code invokes yield, the action is executed. When the action completes, the callback code continues executing. Thus, the code before the yield is like a before action callback and the code after the yield is the after action callback. If the callback code never invokes yield. the action is not run-this is the same as having a before action callback return false.



当我读到这里时,我有点明白了。这是 Rails 指南中的示例
class ChangesController < ApplicationController
around_action :wrap_in_transaction, only: :show

private

def wrap_in_transaction
ActiveRecord::Base.transaction do
begin
yield
ensure
raise ActiveRecord::Rollback
end
end
end
end

那么这里发生了什么? ActiveRecord::Base.transaction 是否以“之前”部分开始,并将 ActiveRecord::Rollback 提升为“之后”部分?这种方法屈服于什么?是节目吗?最后是什么会导致 yield 方法失​​败导致整个回调失败?会是表演 Action 的渲染吗?我不明白。请帮忙。

最佳答案

我的理解如下:

begin
# Do before action...
logger.info 'I am the before action'

# Do the action, which is passed as a block to your "around filter"
# Note that if you were to delete this line, the action will never be called!
yield

# Do after action...
logger.info 'I am the after action'
ensure
raise ActiveRecord::Rollback
end

关于ruby-on-rails - around_action 回调如何工作?需要解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27932270/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com