Rails Interactor- How to Organize your Business Logic
October 13, 2016
An interactor presents components in a system to complete a specific business use-case. It knows how to delegate & get the desired results without carrying out any of the work itself.
Rails interactor is like an object with a single purpose, where every interactor represents one particular task. Prior to interactors, complex business logic were written in ActiveRecord class having multiple responsibilities.
- Easy to Read/Understand : A developer looking at the code base even for the first time would be able to make out what exactly is happening including how to find each of the use-cases.
- Testing is easier : Because every interactor has its own specified task, it is easy to test.
- Low ‘learning’ curve : Just the objects need to be passed into the interactor, that’s it.
- More files : You end up dealing with so many files, however not tough to search.
- More prep-time : No default Railsway of doing things
Add this line to your application’s Gemfile :
Note: Compatible with Ruby > 1.9.3 & > 3 on Rails.
There are two kinds of interactors built into the Interactor library : basic interactors and organizers.
1. Basic Interactors
A basic interactor is a class that defines the call. They are the building blocks ensuring the app/interactors are included in your autoload paths, providing generators for your convenience.
The following command creates an interactors folder under your app directory and a authenticate_user.rb file in the folder.
[code language=”php”]rails generate interactor authenticate_user[/code]
if user = User.login(context.email, context.password)
context.user = user
context.fail!(message: "Invalid Credentials")
rails generate interactor authenticate_user
An organizer is an important variation on the basic interactor. It’s single purpose is to run other interactors. It passes its context to the interactors, one at a time where every interactor may change the context before it’s passed along to the next one.
Run this command to generate organizers.
rails generate interactor:organizerplace_ordercharge_cardsend_thank_youfulfill_order
Organize PlaceOrder, ChargeCard, SendThankYou, FulfillOrder
Note: The context assigned to an interactor contains everything it needs to do.
Interactors are a nice way to reuse operations and explicitly specify a sequence of actions in order to execute business logic. They also provide a way to bubble back errors in any of the operation. In case the error needs to rollback an operation, a rollback method can be specified in the Interactor.
All in all, Interactors are a great way to start cleaning up your code, giving your application a good structure and architecture.
Ever struggled with organizing your Rails app logic ? Let’s help you find a solution.