The service object pattern

Ruby on Rails / Refactoring

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
    end

    def email_domain
      user.email.split("@").last if user.email.present?
    end

    private
    attr_reader :user
  end
end

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.