Method chaining in Ruby

Tram Ho

The chaining method is a very convenient feature for calling multiple methods at once. It not only makes the code more readable, but also reduces the time it takes to write code when we interact with objects and classes

Almost every Ruby on Rails developer has used the chaining method, especially when using ActiveRecord. Recall when we used the following code Model.where(…).order(…) , that is we are using chaining method when those methods are called continuously, “chaining” together.

In this article, I will explore with you how to apply chaining methods to your own code!

Introduction to Method chaining

In this section, we will create a class that contains several methods that will be chaining together, and a method that will eventually give a message. Let’s start with a simple class structure:

Nothing much here because I just want to take a simple example, easy to understand as a base. As you can see, this class contains 3 methods: name() takes a value, age() also takes a value and introduce will give a message. Let’s go to the next step together.

We will save the input of name and age into instance variables so we can use it later.

Ok, after the above installation, we try the chaining method to see if it works:

As you can see, the chaining method is not working. The reason is because in the name and age functions, they return the values ​​in the last line, where the last line here is string for name and integer for age . And these values ​​have no subsequent methods it needs to call. To be clearer, we can go on.

Next we will fix the above methods by returning self rather than string or integer. By returning self , the methods will be chaining together. Let’s try it together?

And try Method chaining:

Alright, so you already guess why the Method chaining works?

In instance functions, when calling self , it is a query to the object that calls that function. In the above example, the person object calls the name function, the person object calls the age function, so self when returning in these functions is the person . Unlike the previous string and integer values, person contains age and introduce functions so it can continue calling the following methods.

In short, the code above works as follows:

  1. person = -> Initialize person
  2.'Baz') -> Assign Baz value to instance variable name and return object person
  3.'Baz').age(21) -> Because the segment'Baz') returns the person object, this segment is equivalent to person.age(21) and continues to return the person object
  4.'Baz').age(21).introduce -> Easy to guess right? This is equivalent to calling person.introduce after the person already has instance variables name = 'Baz' and age = 21

Source of the article

Share the news now

Source : Viblo