Rails Interactor- How to Organize your Business Logic

Rails Interactor
Social sharing

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 was written in Active Record class having multiple responsibilities.

Contents

Understanding the Rails Interactor Pattern

The Rails Interactor pattern is a design pattern that encourages the encapsulation of complex business logic into standalone service objects called interactors. 

Interactors are responsible for orchestrating the flow of operations related to a specific use case or action within your application. 

They help keep your controllers slim by moving business logic out of them and into separate, reusable classes.

Implementing Rails Interactor

To implement the Rails Interactor pattern in your application, follow these steps:

  • Install the ‘interactor’ Gem: Start by adding the ‘interactor’ gem to your Gemfields and running bundle install.
  • Create Interactor Classes: Define your Rail interactors as Ruby classes that include Interactor. Each interactor should implement a call method, which represents the entry point for executing the business logic.
  • Define Business Logic: Move your existing business logic from controllers or models into separate interactor classes. Each interactor should encapsulate a specific operation, such as creating a new user, processing a payment, or updating a record.
  • Use Interactors in Controllers: Invoke interactors from your controllers to trigger the associated business logic. Pass input parameters to the interactor via the context object.

Handle Success and Failure: Interactors can return success or failure outcomes via the context. Use this mechanism to handle different scenarios (e.g., rendering different views based on success or failure).

Benefits :

  • 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 interaction has its own specific task, it is easy to test.
  • Low ‘learning’ curve : Just the objects need to be passed into the interactor, that’s it.

Drawbacks :

  • More files : You end up dealing with so many files, however not tough to search.
  • More prep-time : No default Rails Way of doing things

Installation

Add this line to your application’s Gemfile :
gem “interactor-rails”
Note: Compatible with Ruby > 1.9.3 & > 3 on Rails.

Benefits of Using Rails Interactors

  • Separation of Concerns: Interactors promote a clear separation of concerns by isolating business logic into distinct units, making your codebase more modular and easier to understand.
  • Reusability: Interactors are designed to be reusable across different parts of your application. Once defined, an Interactor can be invoked from multiple controllers or services without duplicating code.
  • Testability: Interactors encourage test-driven development (TDD) by providing a clear and isolated context for testing specific use cases independently of other parts of the application.
  • Flexibility: Interactors allow you to compose complex workflows by chaining multiple interactors together, promoting a flexible and composable architecture.

Usage

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.

rails generate interactor authenticate_user
classAuthenticateUser
  include Interactor
def call
    if user = User.login(context.email, context.password)
context.user = user
    else
context.fail!(message: "Invalid Credentials")
    end
  end
end

rails generate interactor authenticate_user

2. Organizers

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

classPlaceOrder
  include Interactor::Organizer
  Organize PlaceOrder, ChargeCard,  SendThankYou, FulfillOrder
end

Note: The context assigned to an interactor contains everything it needs to do.

Take away…

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 operations , 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.

Rails Interactor is a valuable pattern for organizing and managing business logic in Ruby on Rails applications

By encapsulating complex operations into standalone interactors, you can achieve cleaner, more maintainable code that adheres to best practices such as separation of concerns and the single responsibility principle. 

Incorporate Rails Interactor into your development workflow to improve code quality, testability, and overall developer productivity.

Ever struggled with organizing your Rails app logic ? Let’s help you find a solution.

Your recently viewed posts:

[contact-form-7 404 "Not Found"]
Enter your email address to stay up to date with the latest news.
Holler Box

Orange Exit pop up

Subscribe for the latest
trends in web and
mobile app development
Holler Box

Exit pop up

Sad to see you leaving early...

From "Aha" to "Oh shit" we are sharing everything on our journey.
Enter your email address to stay up to date with the latest news.
Holler Box