Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce an Order to Rails Callbacks

How can one enforce an order of callbacks? For example, how do you ensure that Step 1 happens before Step 2:

after_save do
  logger.info "Step 1"
end

after_save do
  logger.info "Step 2"
end

My actual example relates to using third party gems and ensuring that they have completed (they work on callbacks) before my own callbacks. I must use the same callback (i.e. cannot use a before and after combination).

Thanks!

like image 297
Kevin Sylvestre Avatar asked Dec 08 '10 21:12

Kevin Sylvestre


People also ask

How does callback work in Rails?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

Are Rails callbacks Asynchronous?

Guideline #2: Asynchronous by defaultWhenever we add a callback, that is code that will execute before we can respond to a request. If a class defines 20 callbacks, that's 20 blocks of code that must execute before we can respond to the user.

What is the sequence of callbacks in Rails?

The callback order is as following:after_validation. after_validation_on_create / after_validation_on_update. before_save. before_create.

What is controller callback in Rails?

A callback allows you to run some code (usually a method) automatically when another piece of code runs. In Rails, you'll commonly see callbacks that run before, after or even around other bits of code. Callback functions are minimizing the length of codes in controllers.


1 Answers

If you use class-level callbacks, they are called in the order they are defined.

class Foo < ActiveRecord::Base

  after_save :step1
  after_save :step2

private

  def step1
    # stuff
  end

  def step2
    # stuff
  end
end

For the third-party gem, it depends on how you interact with the gem, but odds are they will be called first because they were loaded first.

I would not recommend using the def after_save style at all, particularly when dealing with a third-party gem.

like image 139
wuputah Avatar answered Dec 01 '22 17:12

wuputah