🏠 HOME
OUR STACK
Services classes are used to perform the business logic of our application. The business logic represents the “real-world” rules related to our app, determining how our data is created, stored, and changed.
They can be called by controllers, commands and other services and they will only call model classes and other services.
Here is an example of our UserService
class:
class UserService
class << self
def create_user(user_attributes, company_attributes)
company = Company.find(company_attributes[:id])
user = User.create(user_attributes.merge(company: company))
if user.accepted?
user.touch(:accepted_at)
end
create_email_notification(user, company)
user
end
end
end
First, you can observe a small difference with other classes we presented earlier. Just after its declaration, you can find class << self
meaning that we will only define class methods..
You can also see that it calls model classes to retrieve the company and create the user (which both are model instances).
Just before returning the newly created user, it calls the create_email_notification
method with the user and its company as parameters. Let’s take a look at its implementation:
def create_email_notification(user, company)
EmailNotificationService.create_email_notification(
{ email: user.email, company: company },
user
)
end
In this method, we make a call to another service, the EmailNotificationService
in order to create a new notification. As we said before, service classes can call and use each other.
After analyzing this piece of code, we can now build a better idea of what is the business logic side of our application. This example showed us what the rules were for the creation of a new user. Without logic, we could have simply done User.create
and be done with it. But in this case, creating a new user means checking a few checkboxes:
accepted_at
timestamps of the user if we need toIt also has some repercussions, the EmailNotificationService class will create a new instance of the notification model, verify a few things and gear a job up in order to take care of this new notification’s sending. This service follows its own business related rules.
<aside> <img src="/icons/playback-previous_lightgray.svg" alt="/icons/playback-previous_lightgray.svg" width="40px" /> Commands
</aside>
<aside> <img src="/icons/playback-next_lightgray.svg" alt="/icons/playback-next_lightgray.svg" width="40px" />
</aside>