DEV Community

BoTree Technologies
BoTree Technologies

Posted on • Originally published at botreetechnologies.com on

Rails: define_method in Models

Rails: define_method in Models

Define_method is a method that allows you to create other methods.

The usual method for defining the method in Rails app is to put your logic between the def and end block.

Now, there’s a situation where you have to build a series of methods and all methods have the same logic and structures to get the batch status.

Let’s go through the example for better understanding.

There are scenarios where you need to check if your batch status is drafted or emailed or approved.

Now, you might say that we will just define one method and accept those statuses as a parameter, and we can use it whenever we want or require.

Yes, you are right!

Example Code:

We have these three methods and all these methods have different names and the same logic. Each method returns the boolean value.

For the above situation, we have a powerful entity named define_method, which will dynamically create methods and will reduce the amount of code.

In our example for 3 different parameters, we can create one object which returns 3 different queries and different method names for those 3 different parameters, which means define_method is provided to the object’s function.

We can use define_method in Ruby on Rails to make one method for the above 3 methods.

Do you want to check this?

Let’s check the below code.

Let’s start from the first, adding methods based on a series of states:

The post Rails: define_method in Models appeared first on BoTree Technologies.

Top comments (0)