We’re so excited! Have you ever experienced the feeling when you eventually found something you were looking for for a long time? As Ruby on Rails agency, we know that sometimes harder to explain than just show and do. But today we found the perfect explanation of the essential Ruby on Rails patterns. Service Objects and Query Objects are explained in series of Błażej Kosmowski articles!
A Service Object (sometimes they can be also called ‘services’) is a simple and powerful pattern, easy to test and with a wide area of use. Most people use Service Object to decompose the ActiveRecord models and keep the controllers slim and readable.
You will find out when to use and how to get most out of Service Object pattern here.
The ease of Service Object implementing is a threat to keeping its implementation under control. Using concise convention when naming service objects, calling and getting results out of them consistently in the same way as well as keeping internals of service object classes simple and readable will ensure that your codebase will benefit from this pattern to a great extent.
Query Objects (also referred to as ‘queries’) is another pattern that helps in decomposing your fat ActiveRecord models and keeping your code both slim and readable.
This pattern helps in abstracting queries, relations and scope chains with complex implementation. By following a few simple rules, we can make sure that this pattern remains readable, flexible and easy to use not only for us but, first of all, for others who might work with our code in the future.
Those rules and examples can be found here.
If you liked this post and want to receive more of useful information – subscribe to our weekly newsletter!
You can search for other articles about Rails news, hacks and tutorials on our blog.