Rails: around_* callbacks

Ruby on-RailsRubyCallback

Ruby on-Rails Problem Overview


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_*.

Any help much appreciated.

Thanks.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

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

So, a typical around_save would look like this:

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

Solution 2 - Ruby on-Rails

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongjbView Question on Stackoverflow
Solution 1 - Ruby on-RailsJacob RelkinView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPan ThomakosView Answer on Stackoverflow