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!
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.
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.
The callback order is as following:after_validation. after_validation_on_create / after_validation_on_update. before_save. before_create.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With