Skip to Content
Course content

195: Hanami Architecture Philosophy

Click on the "Edit" button in the top corner of the screen to edit your slide content.

If you've spent any time in the Ruby ecosystem, you've likely felt the gravitational pull of Ruby on Rails. It's powerful, but if you've worked on a professional Rails project for more than two years, you know the pain: the "Fat Model" syndrome, where a single 2,000-line file handles everything from database queries to email notifications. Hanami was built specifically to solve that architectural rot.

Why should I care about Hanami if Rails already does everything?

Look, Rails is fantastic for getting a prototype off the ground. But Hanami isn't trying to be a "faster" Rails; it's trying to be a more sustainable way to write software. The core philosophy here is decoupling. In Hanami, the framework is just a delivery mechanism. Your business logic doesn't "live" inside the framework; it lives in plain old Ruby objects (POROs) that just happen to be called by the framework.

I like to think of it this way: in Rails, your app is Rails. In Hanami, your app is a set of Ruby services, and Hanami is simply the web-facing shell that routes requests to them. This means when you want to test a piece of logic, you don't have to load the entire heavy framework environment just to check if a calculation is correct.

What's the deal with "Slices" and how do they actually help?

In a typical app, things get messy because the "User" model is used by the admin panel, the public API, and the customer dashboard. Everything is intertwined. Hanami introduces Slices to carve your application into distinct components.

Imagine you're building a Book Inventory System. Instead of one giant app, you'd have an Admin slice and a Catalog slice. Each slice has its own actions, views, and components. They are logically isolated. If the Admin slice needs to change how it handles book uploads, it doesn't risk breaking the Catalog slice's public-facing search page.

# A conceptual look at the directory structure
app/
  slices/
    admin/
      actions/
      templates/
    catalog/
      actions/
      templates/

It's similar to microservices, but without the nightmare of managing network calls between five different servers. You get the organizational benefits of microservices while staying in a single codebase (a "modular monolith").

If the Action isn't for logic, where does the actual work happen?

This is where most people stumble when switching to Hanami. In other frameworks, you're tempted to put your database calls and validation logic right in the controller. In Hanami, an Action has one job: handle the HTTP request and return a response. That's it.

For the actual "work," you create a separate operation class. Let's say we're marking a book as "Loaned" in our inventory system. You wouldn't put that logic in the Action. You'd create a dedicated operation:

# app/slices/catalog/operations/loan_book.rb
module Catalog
  module Operations
    class LoanBook
      def call(book_id:, user_id:)
        # 1. Validate availability
        # 2. Create loan record
        # 3. Update book status
        # 4. Trigger notification
      end
    end
  end
end

Then, your Action simply calls this operation. This makes your code incredibly easy to test because you can test LoanBook in complete isolation from the web request.

Why split Entities and Repositories instead of just having a Model?

This is the "secret sauce" of Hanami's persistence layer. In most Ruby apps, the Model is a god-object: it knows how to validate data, how to save itself to SQL, and how to calculate business totals. Hanami splits this into Entities and Repositories.

  • Entities: These are simple data objects. They don't know the database exists. They just hold attributes (like title or isbn).
  • Repositories: These are the only objects allowed to talk to the database.

Why do this? Because it prevents your business logic from becoming leaked SQL. If you decide to switch from Postgres to a NoSQL store or a third-party API for your book data, you only have to change the Repository. Your Entities and Operations remain untouched. I've seen this save weeks of refactoring time in legacy projects.




📋 Practical Task

Refactor a "Fat Action" into a Hanami Operation

You've inherited a piece of code in a Book Inventory system where the developer ignored the Hanami philosophy and crammed all the logic into the action. Your task is to decouple this.

The current messy action:

# app/slices/catalog/actions/books/create.rb
module Catalog
  module Actions
    module Books
      class Create < Catalog::Action
        def handle(request, response)
          book_params = request.params[:book]
          
          # PROBLEM: Business logic and persistence in the action!
          if book_params[:isbn].nil?
            response.status = 422
            response.body = "ISBN is required"
          else
            repo = BookRepository.new
            repo.create(book_params)
            response.status = 201
            response.body = "Book created successfully"
          end
        end
      end
    end
  end
end

Your Goal:

  1. Create a new class Catalog::Operations::CreateBook that handles the ISBN validation and the repository call.
  2. Refactor the Catalog::Actions::Books::Create action to instantiate the operation and call it, removing all business logic from the action itself.
  3. Ensure the Action still returns the correct HTTP status codes based on the outcome of the operation.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.