Callback in Rails and its application

Tram Ho

Callback in Rails:

1. Introduction

Before coming to Callback, we need to understand what is the life cycle of an object? Hmmm if we try to consider the life cycle of a cat it will be born, grown and lost, so is an object in Rails. The life cycle of an object in Rails consists of (Add, Modify, Delete) and Rails has created hook points or callbacks in the life cycle of an object so we can manipulate this object.

1.1. What is callback:

  • Callback is a method of Active Record, called at some point in the life of the object.
  • Used to execute logical methods before or after the object has made a change. For example: We want our email fields in the database to be all lower case letters, but for users, they can enter as they like ( [email protected] ). So how should we handle this? => Before saving in the database we give all the lowercase letters => We use Callback before_save.

2. Make Callback:

Because this Callback guy just revolves around the events of the object (create, update, destroy), it MUST be declared in the model of that object. For example, write a regular method and then use the macro-style to declare it as a Callback

=> Through here, we see before we save this User object in the database, then implement the function ensureemailvalid (turn email into lower case) to ensure the correctness of data before storing it in the database.

3. Callback List:

Here is a list of Active Record’s Callbacks, sorted in the order of invocation during the operation of an object:

3.1 Add

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_create
  • around_create
  • after_create
  • after_save
  • after_commit / after_rollback

3.2 Edit

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_update
  • around_update
  • after_update
  • after_save
  • after_commit / after_rollback

3.3 Delete

  • before_destroy
  • around_destroy
  • after_destroy
  • after_commit / after_rollback

3.4 after_initialize and after_find

Maybe in the process of coding, we rarely pay attention to these two men, but these two men have a huge role.

  • The afterinitialize callback is called when the object is initialized or loaded from the database.
  • The afterfind callback is called when the Active Record loads a record from the database.
  • afterfind is called before afterinitialize if both are defined

=> So why do I say it has such a big role, then you see that every time an object is initialized, the Callback afterinitialize is always called or when loading an object from the database, the Callback afterfind then Callback afterinitialize is called. So these 2 callback guys are always called but sometimes we don’t know, knowing this can help you optimize your code:>.

4. Run Callback

Here are the methods that will run the callback:

  • create
  • create!
  • destroy
  • destroy!
  • destroy_all
  • save
  • save!
  • save (validate: false)
  • Toggle!
  • update_attribute
  • update
  • update!
  • valid? afterfind will be called when these find methods are called:
  • all
  • first
  • find
  • find_by
  • find_by_ *
  • find_by_ *!
  • find_by_sql
  • last afterinitialize will be called whenever a new object is instantiated

5. Ignore Callbacks

As with validation, you can ignore callbacks using the following methods:

  • decrement
  • decrement_counter
  • delete
  • delete_all
  • increment
  • increment_counter
  • Toggle
  • touch
  • update_column
  • update_columns
  • update_all
  • update_counters => Note: These methods should be used with caution because data validates or logic are stored in the callback. So ignoring these callbacks can result in invalid data.

6.Callbacks are conditional

In programming, there are many circumstances and sometimes we need to know how to optimize our code to avoid clean code. So Rails provides us with conditions that apply to Callback:

6.1 Use : if and : unless to Symbol

Before saving will call a normalizecardnumber callback if paidwithcard? returns * true *

6.2 Use : if and *: unless * to Proc

6.3 Multiple conditions for Callbacks

=> Callback is a very powerful tool that gives our Rails, can be quite different from other programming languages, but we should not abuse use no.Chi use callback when logic concerning the body of the object. This will avoid the subject having to deal with problems beyond its own control. Hope the article will help you understand more about Callback and use it in an optimal way.

Reference source

Share the news now

Source : Viblo