Going further with Service Objects in Ruby on Rails

Written by rob__race | Published 2017/02/20
Tech Story Tags: ruby-on-rails | ruby | rails | programming

TLDRvia the TL;DR App

Note: This tutorial is an excerpt for the service object chapter in my book Building a SaaS Ruby on Rails 5. The book will guide you from humble beginnings by deploying an app to production. If you find this type of content valuable, the book is on sale right now!

Also, you should check out this project called Bullet Train by a good acquaintance of mine, that will save you weeks of development by starting you off with all the features that are the same in every SaaS, so you can focus on what makes your app unique.

As a follow up to the recent post about Service Objects, Service Objects in Ruby on Rails…and you, I wanted to go deeper into Service Objects subject with details such as keeping objects to a single responsibility, better error handling, and clearer usage. To show you the differences I will be refactoring the Service Object I created in the first post on Service Objects.

I would like to also point out some blog posts that influenced this refactor such as http://blog.sundaycoding.com/blog/2014/11/25/my-take-on-services-in-rails/ and http://multithreaded.stitchfix.com/blog/2015/06/02/anatomy-of-service-objects-in-rails/.

class NewRegistrationServicedef initialize(params)@user = params[:user]@organization = params[:organization]end

def performorganization_createsend_welcome_emailnotify_slackend

private

def organization_createpost_organization_setup if @organization.saveend

def post_organization_setup@user.organization_id = @organization.id@user.save@user.add_role :admin, @organizationend

def send_welcome_emailWelcomeEmailMailer.welcome_email(@user).deliver_laterend

def notify_slacknotifier = Slack::Notifier.new "https://hooks.slack.com/services/89ypfhuiwquhfwfwef908wefoij"notifier.ping "A New User has appeared! #{@organization.name} - #{@user.name} || ENV: #{Rails.env}"end

end

Let’s start by calling out the fact that we’re putting a bunch of different responsibilities into one Service Class. Additionally, it’s not really following the errors or successes through the parent class into the controller that requested the Service. To start remedying that we will split off each of the responsibilities into their own classes.

Before showing the code for these classes, I would also like to touch on another change in the new service object, being the use of build to inject the depending classes:

class NewRegistration

def self.buildnew(OrganizationSetup.build, AdminUserSetup.build, SendWelcomeEmail.build, NotifySlack.build)end

def initialize(organization_setup, admin_user_setup, send_welcome_email, notify_slack)self.organization_setup = organization_setupself.admin_user_setup = admin_user_setupself.send_welcome_email = send_welcome_emailself.notify_slack = notify_slackend

....

The build/new technique has been previously proposed in a blog post by Piotr Solnica (of rom_rb and dry-rb fame) at http://solnic.eu/2013/12/17/the-world-needs-another-post-about-dependency-injection-in-ruby.html. With the idea being can call a build method on a Service class to instantiate the object and any dependents. If it is a child with none, you would just call new . This way the injected classes can be passed in, instead of hardcoded and can pay dividends when setting up your objects to be tested.

Without further ado, here are the new child classes:

…setting up the organization(aka, saving the passed in record)

# app/services/new_registration/organization_setup.rbclass NewRegistrationclass OrganizationSetup

def self.build  
  new  
end

def call(organization)  
  organization.save!  
end

endend

…setting up the initial user from the newly created organization

# app/services/new_registration/admin_user_setup.rbclass NewRegistrationclass AdminUserSetup

def self.build  
  new  
end

def call(user, organization)  
  user.organization\_id = organization.id  
  user.save  
  user.add\_role :admin, organization  
end

endend

…sending the welcome email

# app/services/new_registration/send_welcome_email.rbclass NewRegistrationclass SendWelcomeEmail

def self.build  
  new  
end

def call(user)  
  WelcomeEmailMailer.welcome\_email(user).deliver\_later  
end

endend

…and finally, pinging slack

# app/services/new_registration/notify_slack.rbclass NewRegistrationclass NotifySlack

def self.build  
  new  
end

def call(user, organization)  
  notifier = Slack::Notifier.new "[https://hooks.slack.com/services/89hiusdfhiwufhsdf89](https://hooks.slack.com/services/89hiusdfhiwufhsdf89)"  
  notifier.ping "A New User has appeared! #{organization.name} - #{user.name} || ENV: #{Rails.env}"  
end

endend

In the new version of the services I have split up the child components a little differently to better embody each of the individual child services and potentially handle exceptions. Now, that we have our child services, we can call them in our parent service

# app/services/new_registration.rb

def call(params)user = params[:user]organization = params[:organization]

begin  
  organization\_setup.call(organization)  
  admin\_user\_setup.call(user, organization)  
  send\_welcome\_email.call(user)  
  notify\_slack.call(user, organization)  
rescue => exception  
  OpenStruct(success?: false, user: user, organization: organization, error: exception)  
else  
  OpenStruct(success?: true, user: user, organization: organization, error: nil)  
end  

end

....

As you can see, another change from the previous version of the NewRegistration service is that we are no longer using a .perform method and now using .call . Why is this important? Well one, it is actually a lot more common than perform, even the common understood standard, which commenters here and elsewhere have pointed out. Additionally, .call responds to lambdas which may help you out using these objects elsewhere.

We parse out the parameters much like we did in the previous version, but now into regular variables instead of instance variables as they are being passed into the new child services in the same public .call method. The order and ‘waterfall’ of items to perform stay relatively the same throughout both versions though.

Now that we have individual child services we can catch exception from any of the services in a begin...rescue..end block. That way, we can catch an issue like the organization not saving, pass it back up through the parent object and the controller that called it to handle the exception. Additionally, now we are passing back what is essentially an results object with OpenStruct to the controller as well. This object will hold :success? , objects that were passed in to be returned, and any errors from the services.

With all these changes, the way we can call the Service from our controller is slightly different, but not much:

result = NewRegistration.build.call({user: resource, organization: @org})if resultredirect_to root_path(result.user)else** redirect_to last_path(result.user), notice: 'Error saving record'end

If you want to go a lot deeper on success/error paths, chaining services and handling states with a pretty lightweight DSL, I recommend checking out https://medium.com/p/chain-service-objects-like-a-boss-35d0b83606ab from benjamin roth. As always with Ruby, the size of your app, business logic, readability needs or styles, and complexity can cause your needs for simple classes to DSLs to vary.

Lastly, now an example of how easy it can be to test the newly refactored service

# spec/services/new_registration_test.rbdescribe NewRegistration docontext "integration tests" dobefore do@service = NewRegistration.build@valid_params = {user: Factory.create(:user), organization: Factory.build(:organization)}end

 it "creates an organization in the database" do  
  expect { @service.call(@valid\_params) }.to change { Organization.count }.by(1)  
 end

...etc, etc

There you have it, refactored Registration Service objects that better encapsulates the Single Responsibility Principle(it may not be perfect to the most religious of followers), better result handling, improved readability, and improved dependency handling. Obviously, almost any code can continuously be improved and I look forward to the internet to pick apart this version of the Registration Service. :)


Published by HackerNoon on 2017/02/20