Rails:around_ *回调


Answers:


178

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

顺序是这样的:beforearoundafter

因此,典型的around_save情况如下所示:

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

4
这是有道理的,不在Rails官方指南中。
Dan S.

120

在动作周围以及在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

14
对我来说,这是最有启发性的答案。谢谢你,朋友。
2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.