Refactoring Ruby on Rails

Ruby on Rails / Refactoring – service object pattern

Ruby on Rails / Refactoring – service object pattern February 3, 2018Leave a comment

This refactoring pattern is very simple but I found it very useful in every app I was working on. You can use it wherever class or method has to much code. I used to stick to these rules when creating services:

  • use _service suffix in every service class name
  • respect single responsibility principle but it’s more a general rule than something specific to the service pattern

Let’s build some sample service class to demonstrate idea behind it:

module Users
  class EmailDomainService
    def initialize(user)
      @user = user
    def email_domain"@").last if
    attr_reader :user

It’s a very simple and small but very useful class. You shouldn’t have many lines of code inside your services. They should do only small things, serve only one thing at once.

You can use this pattern when you will be refactoring large class by moving small portions of code to separated services.

Photo by Stefan Lorentz from Pexels

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

Leave a Reply

Your email address will not be published. Required fields are marked *