Active Callbacks

never from her... :/

·

2 min read

Hello, fellow earth beings.

Evening!

In the previous article, we sent a :welcome_email every-time a new user is created.

Let's assume that we are building a secure banking website/portal and we need to send a mail for each privileged action such as password update, online money transfer, application for a new credit/debit card etc...

If a user avails any one of these services, we intend to send an alert email/sms to the user account.

Let's call these actions,

  1. def transfer_money; end
  2. def update_password; end
  3. def new_card_apply; end

As we intended, we need to send an alert mail for either one or more of these actions triggered by the user so that the user knows that there is some activity happening in the said user's bank account.

Let's call it :alert_mail.

Instead of adding,

def action
  AlertMailer.with(:current_user).alert_mail.deliver_later
end

to all the actions we can simply use a callback action.

Rails provides several callback methods/helpers to make this easier.

For example in this scenario we could use:

def UsersController < ApplicationController
  # CALLBACKS
  after_action :do_this, only: [:transfer_money, :update_password, :new_card_apply]
  # ...
  private
  def do_this
    # send mail or any other action
    # ...
  end
end

This enables your controller to execute :do_this action every-time the user triggers any one of these actions: [:transfer_money, :update_password, :new_card_apply].

There are many callback helper such as:

  1. before_create, after_create
  2. before_save, after_save
  3. before_validation, after_validation
  4. around_update, around_destroy
  5. before_destroy, after_destroy

and many more...

Please refer to the Rails Guides: Active Record Callbacks

How awesome is Rails!

Going to enjoy weekend. Not really :/

Thank you for reading today.

Please do subscribe to the newsletter.

Love,

M.

liked_the_post == true ? comment and share : comment and share