Service object in Rails

Tram Ho

Ruby on Rails provides everything you need to quickly create your application, but as your application starts to develop, you will experience situations where models and controllers swell, in branches, and difficult to control when dealing with complex business and logic, including functions that require us to interact with many different Models, not targeting a specific model.

Service Object is one of the solutions to this problem. It was born as a container for various business logic in which the processing object did not belong to any model.

The benefit of Service Object is that it helps us to focus all of the functionality logic into a separate object without having to subdivide it into controllers and models as usual. We always call that object when we need it. Because the logic block is focused on one object, it will minimize the controller and model a lot, the code clean and the maintain process is also less strenuous in the future.

service object class

classes are a good choice if you want to save data to instance variables.

service object module

If you don’t want to save data to instance variables, then a module is a lighter option

how to use the service object

Normally in Rails system services will be concentrated in the app / services directory . Depending on the specificity and complexity of the project, we can subdivide the services into many sub-categories. In this example, I will create a service object named CalculatorService:

The CalculatorService class is initialized with the parameters number_1, number_2, method and has methods of addition , subtraction , multiplication , division

We can call the service object wherever and whenever we need to use it

Note: if your service object is a module then you must include or extend it depending on your intended use.


The article aims to share a bit of my knowledge and basic usage of Service Object, the article is still limited, thank you for reading.

References: /2020/06/17/using-service-objects-in-ruby-on-rails.html

Share the news now

Source : Viblo