ActiveModel::Callbacks

Prateek vyas
2 min readJun 29, 2022

--

Here’s how you can use ActiveRecord like callbacks in a ruby class!

ActiveModel::Callbacks

Ever wondered of using the ActiveRecord callbacks in a pure ruby class ?

If so, Here’s the solution!

All you need to do is require ‘active_model’ in your ruby file. Because ActiveModel provides us various modules used in developing classes that need some features present on ActiveRecord.

One of the Module which is discussed in this blog post is ActiveModel::Callbacks, which gives us ActiveRecord style callbacks.

The instance method provided by ActiveModel::Callbacks is define_model_callbacks(*callbacks). And the *callbacks can be [:create, :update]. so it will give you all the 6 possible callbacks 3 for create and 3 for update which are before_create, around_create, after_create and rest 3 for update (before_update, around_update, after_update).

define_model_callbacks :update
=> before_update, after_update, around_update
define_model_callbacks :create
=> before_create, after_create, around_create

you can also use only options if you specific callbacks like before_create.

define_model_callbacks :create, only: :before
=> before_create

Let’s understand with the example below:

class Entrepreneur
include ActiveModel::API
extend ActiveModel::Callbacks
attr_accessor :name
define_model_callbacks :update
before_update :put_salutation def update
run_callbacks :update do
self
# run_callbacks :update do...will execute all the callbacks #related to the update (before_update here)
end
end
# this will be invoked before the method 'update'
def put_salutation
self.name = 'Mr ' + name
end
end
entrepreneur = Entrepreneur.new(name: 'pratik vyas')
p entrepreneur.update
#=> #<Entrepreneur:0x00007f86bb92ad08 @name="Mr pratik vyas">

If you’re not familiar with include ActiveModel::API. Please go through ActiveModel::API.

here i have used instance method define_model_callbacks :update. which gave me the callback before_update, around_update and after_update.

I have used before_update callback in the above code.

So what happens is i created a object entrepreneur with the name pratik vyas, and called a method update on it. So when update method starts executing it see’s that there is run_callbacks :update so it checks that if there’s a before_update callback method is defined or not, If so, then it will execute it first and then get back to the update method execution.

Therefore the output we get is <Entrepreneur:0x00007f86bb92ad08 @name=”Mr pratik vyas”>

Thanks for giving it a read!

Happy coding :)

--

--

Prateek vyas
Prateek vyas

Written by Prateek vyas

Hello i am prateek vyas working as a ruby developer

No responses yet