[英]how rails around_action works with return statement
I am new to the ruby and RoR world and I have recently learned about blocks.我是 ruby 和 RoR 世界的新手,我最近了解了块。 I have read that return inside block actually returns from the top most function that called it我已经读过返回块内实际上是从调用它的最顶层函数返回的
for example例如
def test
value = yield
puts value
end
# prints "return inside block"
test do
"return inside block"
end
# prints nothing
test do
return "return inside block"
end
so if this is how blocks and "return" works in ruby, how come around_action don't behave the same?因此,如果这是块和“返回”在 ruby 中的工作方式,那么 around_action 的行为怎么会不一样?
for example例如
class TestController < ApplicationController
around_action :aroundy
def test
render json: {amit:"hello"}
puts "hello"
return
end
# prints after even though the action "test" calls return
def aroundy
puts "before"
yield
puts "after"
end
end
How is it possible that the code continues to run after the yield if I called return inside the action?如果我在操作中调用 return ,代码怎么可能在 yield 之后继续运行?
There's a big difference between these two situations: your action test
is a method, not a block.这两种情况有很大的不同:你的动作test
是一个方法,而不是一个块。 This alone is enough to throw out all expectations that return
should behave the same way as it does in blocks.仅此一项就足以排除所有期望return
行为方式与它在块中的行为方式相同。
In addition, the way it's called is not as simple as in your first snippet.此外,它的调用方式并不像您的第一个代码段那样简单。 Here 's how around_action
is implemented in rails, for example: 以下是在 rails 中实现around_action
方式,例如:
define_method "#{callback}_action" do |*names, &blk|
_insert_callbacks(names, blk) do |name, options|
set_callback(:process_action, callback, name, options)
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.