Ruby-on-rails Rails:around_* 回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4998553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:25:29  来源:igfitidea点击:

Rails: around_* callbacks

ruby-on-railsrubycallback

提问by gjb

I have read the documentation at http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html, but don't understand when the around_*callbacks are triggered in relation to before_*and after_*.

我已阅读http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html 上的文档,但不明白何时around_*触发与before_*和相关的回调after_*

Any help much appreciated.

非常感谢任何帮助。

Thanks.

谢谢。

回答by Jacob Relkin

around_*callbacks are invoked beforethe action, then when you want to invoke the action itself, you yieldto it, then continue execution. That's why it's called around

around_*回调在动作之前被调用,然后当你想调用动作本身时,你要调用yield它,然后继续执行。这就是为什么它被称为around

The order goes like this: before, around, after.

顺序是这样的:before, around, after

So, a typical around_savewould look like this:

所以,一个典型的around_save看起来像这样:

def around_save
   #do something...
   yield #saves
   #do something else...
end

回答by Pan Thomakos

The around_* callback is called around the action and inside the before_* and after_* actions. For example:

围绕动作和 before_* 和 after_* 动作内部调用 around_* 回调。例如:

class User
  def before_save
    puts 'before save'
  end

  def after_save
    puts 'after_save'
  end

  def around_save
    puts 'in around save'
    yield # User saved
    puts 'out around save'
  end
end

User.save
  before save
  in around save
  out around save
  after_save
=> true