An Introduction To Hanami 2.0

Ruby on Rails is one of the most popular Ruby frameworks, but it's not the only one. Hanami 2.0 is faster than Rails and packed with exciting features—it might be the tool you need for your next project!

Ruby on Rails is one of the most popular Ruby frameworks in developer circles, but it's not the only one. There are lots of other relatively unknown frameworks, including Roda, Sinatra, and Goliath. Some of these are faster than Rails, packed full of interesting features, and might be the very tool needed for your next project.

In this article, we'll take a look at one such framework: Hanami 2.0.

What is Hanami?

Hanami is a Ruby framework introduced about five years ago and initially called Lotus. The framework is the brainchild of developer Luca Guidi.

On the project's website, Hanami is described as "a modern framework for Ruby". It features fast response times and security features by default, and it is very lightweight.

But even so, you may be wondering what "Hanami" means? Well, it comes from the Japanese language and means "flower viewing", a rather popular activity where people sit together to enjoy flower blossoms.

From descriptions given by the language's developer, the name Hanami is a tribute to the rich Japanese heritage that the Ruby language is built upon, something the developer, Luca Guidi wanted to highlight in the Hanami framework.

In this article, we'll focus more on the latest version, 2.0.

Why You Should Use Hanami, and Why You Might Need (Yet) Another Ruby Framework

As we pointed out in the very beginning of this article, Hanami is just one of several Ruby frameworks.

Ruby on Rails is the most popular of the Ruby frameworks. It’s very modular and general purpose. It could be said that it's main promise is that you can use it to go from zero to having a working app prototype in a matter of hours.

Then there's the less popular, but no less powerful Sinatra? What's it's super-power? Well, if you want to build something super lean and blazing fast using Ruby, say an HTTP server API, then Sinatra would be a great choice.

According to Luca Guidi, the creator of Hanami, the overall goal he wanted to achieve with the framework was to give developers a tool that would help them have as much productivity as possible.

Did he deliver on that promise?

Let's take a look at some of the framework's stand-out features:

  • Multiple apps within a project - Whereas a Rails app is essentially one large modular app, in Hanami, you can have multiple apps within the main project. Inside the main folder tree, there is a folder called "apps", in which you can have multiple apps in residence (e.g., a JSON-driven API and a regular web application within one app/project).

  • Fast - At its heart, the framework was built on the idea of minimalism. It tries very hard to avoid the large app structure that is a major feature of a rival like Rails. This focus on minimalism helps greatly in the speed department. Furthermore, it's said to use 60% less memory compared to other Ruby frameworks.

  • Features over MVC - Whereas Rails is heavily opinionated on how an app should be built, Hanami (especially version 2.0) tries to chart a different path by focusing on building around features. Although explaining this aspect of the framework in detail is beyond the scope of this article, in a nutshell, it means that instead of the framework dictating how you should build an app following some "set rules" (i.e., MVC structure), with Hanami, the developer decides how to build an app based on the desired features.

  • Callable objects - Hanami takes the idea of object-oriented programming to a whole new level. Using a shared mixin-injection system, it is very easy to compose complex objects based on other, much simpler objects.

Of course, this is a very simplified features list. Hanami 2.0 is significantly more than that, and you are highly encouraged to visit the project website to learn more about the framework.

Now that we have a bit more information on what it's all about, let's take a look at what you can do with it.

What is Hanami Good For?

Depending on what you are building, you may find that a general-purpose language like Rails is a great choice.

However, Hanami's unique attributes can help you build for specific use cases, such as when you need the following:

  • Speed - Today, it's more of a rule than an exception that your app needs to be fast, and languages and frameworks that can deliver on this tend to have an upper hand. Hanami's low memory footprint and very defined app structure make it a worthwhile choice for your next app that needs to be as fast as possible, such as an API.

  • Simplicity and maintainability - When you use a framework like Rails, you know how fast your codebase can grow depending on what you are building. Even with testing, such large code structures tend to hide bugs and other inefficiencies. As a solo developer or small team, you may not have the resources to properly maintain such an application. Hanami tends to favor breaking functionality down into its smallest possible parts, which means that adding features, refactoring, and bug tracking tends to be easier.

  • Security - By default, Hanami apps come with various web security features baked in, including content security policy, X-frame headers, and automatic escaping.

Now that we have a good idea of what the framework is about, let's get into the fun-stuff and build a simple Hanami 2.0 app.

Let's Build a Simple Hanami App

The best way to get a taste of what Hanami is all about is to roll up our sleeves and build something with it. The app we are building is a very simple blog app.

Using this example, you will learn how a Hanami 2.0 app is structured.

Prerequisites

Before we get started, make sure you have the following:

  • Ruby installed - Ensure you have Ruby 2.3+ installed on your local development machine. We recommend using a Ruby version manager, such as RVM or rbenv.

  • Bundler installed - Make sure to have the gem manager Bundler locally installed.

  • Local SQLite 3+ installation - Although you can use the Postgres database, in this example, we'll be using an SQLite 3+ database. In case it's not already installed, use Bundler to install it with bundle install sqlite3.

  • NodeJS - Node 16+ installed (as of writing this article). You can use Node version manager (NVM) to manage different Node versions.

  • Overmind installed - Overmind is a process manager that lets you run several processes from a single terminal. Also, make sure you have tmux, a terminal session manager, installed as it's required by Overmind.

Important note: Hanami 2.0 is still in alpha and under heavy development at the time of this writing, so things may break.

Step 1: Setup

With the Hanami CLI for version 2 under heavy development, we'll use the version 2.0 starter template available here. The completed sample app we'll build is available here.

To follow along, go ahead and clone the repo and rename it to 'hanami2-blog-app'.

git clone https://github.com/hanami/hanami-2-application-template.git hanami2-blog-app

Next, in the terminal, switch to the project folder and run bundle to install the required gems.

Then, go ahead and rename all instances of the original template project name to the name of your new app, "hanami2-blog-app" in this case, using the following command:

./bin/install hanami2-blog-app

With this done, run the following in the terminal:

./script/setup

This will setup a couple of things within the project, including creating the app database.

Step 2: Run the App

Let's now run our example app just to see what a basic Hanami 2 app looks like. Go ahead and run the following command:

./script/server

Now, if everything went as planned, a visit to localhost:3000 should show your app running.

Before we dive into creating our app's blog functionality, it would be prudent to have an overview of how a Hanami 2 app is structured, especially if you are coming from a Rails background since it has its own way of doing things.

Overview of a Hanami 2 App Structure

Hanami really pushes the concept of abstraction or separation of concerns to the limit.

If you are coming from a Rails background and it feels a bit confusing, the simplified diagram below shows you how that abstraction is done in Hanami vs. Rails.

Hanami vs. Rails abstraction

Routes

The Hanami router and its Rails counterpart are generally the same. They both recognize URLs and dispatch them to their relevant actions (in Hanami) and controller actions (in Rails).

Actions vs. Controllers

Instead of having controllers with actions in them, Hanami's abstract style features bare actions, which are not encapsulated in any sort of "controller".

"Models" vs. Models

Whereas you have models as the persistence interface in Rails, Hanami utilizes ROM architecture, which gives you repositories, relations, and entities. You also get "contracts", which act as your app's validation engine.

Views

In Rails, views are generally composed of the actual views, layouts, and partials. Hanami uses DRY view to abstract away this functionality into views, parts, and templates.

There's obviously a whole lot more to Hanami's abstraction style, and so to learn more, we recommend visiting the project's website

Now that we have a general idea of what Hanami looks like under the hood, let's keep going.

Step 3: Creating and Viewing Blogs

The image below shows how a simple http GET request is handled by Hanami.

Hanami http request

We'd like to create a few blog articles and be able to view them, so we'll start from the router and continue all the way to structuring the view.

Routing Hanami Style

When a web visitor requests a certain page from a browser, the request is taken up by the Hanami router and matched to a relevant action.

In your code editor, open the routes file, found under config/routes.rb. The default file is shown below:

# frozen_string_literal: true

# ../config/routes.rb

require "hanami/application/routes"

module Hanami2BlogApp
  class Routes < Hanami::Application::Routes
    define do
      slice :main, at: "/" do
        root to: "home.show"
      end
    end
  end
end

As you can see, there's a root route defined, which maps to the home#show action. This is the default root that comes with the application template.

Let's add two more routes: one for showing a list of blogs (the index) and another for showing an individual blog post.

As of the writing of this article, Hanami CLI is still in development, so convenient generators, such as hanami generate..., are not yet available.

Edit your routes file to include the two routes as follows:

# frozen_string_literal: true

# ../config/routes.rb

require "hanami/application/routes"

module Hanami2BlogApp
  class Routes < Hanami::Application::Routes
    define do
      slice :main, at: "/" do
        root to: "home.show"

        get '/blogs', to: "blogs.index"
        get '/blogs/:id', to: "blogs.show"
      end
    end
  end
end

From the Router to Hanami Actions

When the Hanami router receives a request, it maps it to the corresponding action.

In our case, the request for the blog listing (i.e., .../blogs) will map to the index action, while the one to .../blogs/:id will map to the show action.

Now we’ll switch to the actions.

Create a folder called "blog" in slices/min/lib/actions. Then, within this folder, create an index.rb file:

Creating action files

For the index action, edit is as follows:

# frozen_string_literal: true

#../slices/main/actions/blog/index.rb

module Main
  module Actions
    module Blog
      class Index < Main::Action
        include Deps[
          repo: 'application.persistence.repositories.blogs'
          ]

        def handle(req,res)
          res.render view, blogs: repo.all
        end
      end
    end
  end
end

In Hanami, "repositories" are used to fetch data from the database. Therefore, the line include Deps[repo: 'application.persistence.repositories.blogs'] specifies the repository that will be used by the index action to fetch data from the database (We'll define the data fetching layer after the actions).

Then there's the block:

def handle(req,res)
  res.render view, blogs: repo.all
end

This is what handles incoming requests from the router and renders the corresponding view with the blogs variable included.

The obvious next step is to jump to the view layer, but before we do that, we need to work on the data layer.

Working With Data in Hanami

As mentioned earlier, in Hanami, entities, repositories, and relations make up what we call the data layer.

"Relations" define how data is fetched from the database. You would also define scopes and other database-specific queries in relations.

"Repositories", however, are database-agnostic. They mediate between entities and relations.

An "entity" is where you define domain-specific logic.

After this very condensed overview of the Hanami data layer, let's continue with creating some data for our app.

We could manually create migration files, but since we have access to the awesome Hanami CLI generator (although it has limited functionality for now), let's use it to create a migration that will be used to create the blogs table for our app.

The other reason we want to create migrations using the CLI, other than convenience, is because we want the timestamps applied automatically.

hanami db create_migration blogs

This creates a migration under the db folder. For now, this file is a bit empty and rather useless to us. Edit it as follows:

# frozen_string_literal: true

ROM::SQL.migration do
  change do
    create_table(:blogs) do
      primary_key :id
      column :title, String 
      column :body, String 

      column :created_at, DateTime, null: false
      column :updated_at, DateTime, null: false
    end
  end
end

Then apply the migration to create the blogs table.

hanami db migrate

For the purposes of our very simple blog app, we will seed the table with some data.

Find the seeds file (under the db folder) and edit it accordingly.

# Seeds

# create some blogs
blogs = Main::Container['application.persistence.repositories.blogs']

20.times do |i|
    blogs.create(title: "Blog no.#{i}", body: "This is blog no. #{i}", created_at: Time.now, updated_at: Time.now)
end

Then run it:

hanami db seed

With that, we should now have a few blog posts to work with.

Fetching Data

Remember, in Hanami, relations are used to fetch data from the database. Therefore, let's create the relation that will fetch blogs from the database.

Under the lib folder, there's a folder with the name of the app (in our case, it's "hanami2_blog_app"), and within it is a "persistence" folder. In there, you should find two folders: "relations" and "repositories" (In case the repositories folder is not available, just create it manually.)

Then, in the repositories folder, create a file called "blogs.rb" and another with the same name in the "relations" folder.

Your app structure should now look similar to the one shown below:

Relations and repositories.

In the relations folder, we define the schema for mapping to the relevant table (the blogs table in this case) in a file we call "blogs.rb":

# frozen_string_literal: true

#../lib/hanami2_blog_app/persistence/relations

module Persistence
    module Relations
      class Blogs < ROM::Relation[:sql]
        schema(:blogs, infer: true)
      end
    end
end

Then, in the repositories folder, we define a repository file called "blogs.rb", which will define how we fetch and create blogs in the database:


#../lib/hanami2_blog_app/persistence/repositories

module Sandbox2
    module Persistence
        module Repositories
            class Blogs < Repository[:blogs]
                commands :create 

                #..fetches all blogs
                def all 
                    blogs.to_a
                end

                #...fetches a single blog
                def by_id(id)
                    blogs.by_pk(id).one
                end
            end
        end
    end
end

So far, we've created some routes, mapped them to appropriate actions, seeded our database, and created a layer to access the data using relations and repositories.

Now let's see how views are handled in Hanami.

Viewing the Data

Since ours is a very simple blog app, we'll only use the view and template bits for now.

Let's start by passing the data from the relevant action into a "view". For the blog index view, create an index.rb file under .../slices/main/lib/main/views/blog/

# frozen_string_literal: true

#.../slices/main/lib/main/views/blog/index.rb

module Main
  module Views
    module Blog
      class Index < View::Base
        expose :blogs
      end
    end
  end
end

Here, we are telling the view that data will be passed into it via the blogs variable from the related action.

Now all that's left for us to be able to view the blogs data on the web browser is to create a template view to render the data.

h1 A listing of all blogs

ul
  - blogs.each do |blog|
    li: a href="/blogs/#{blog.id}" = blog.title

Templates can be in erb, haml, or slim. What's available by default from the Hanami 2 template project is slim.

In the template, we are doing a simple iteration on the blogs variable to give us a list of blog titles that should now be viewable on the browser.

script/server

Assuming nothing breaks, head over to localhost:3000/blogs and view your list of blog posts.

Wrapping Up

Now that you have an overview of what Hanami 2 is all about and even created a simple app from routes all the way to the view template, we challenge you to take your learning a bit further.

You will notice that we created a show route but not it's action or the subsequent view and template for it. Why don't you take what you've learned so far and create an action for the show route, as well as the show view and template.

Happy coding, and keep learning!

What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Aestimo Kirina

    Aestimo is a family guy, Ruby developer, and SaaS enterpreneur. In his free time, he enjoys playing with his kids and spending time outdoors enjoying the sun, running, hiking, or camping.

    More articles by Aestimo Kirina
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.”
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial
    Are you using Sentry, Rollbar, Bugsnag, or Airbrake for your monitoring? Honeybadger includes error tracking with a whole suite of amazing monitoring tools — all for probably less than you're paying now. Discover why so many companies are switching to Honeybadger here.
    Start free trial
    Stop digging through chat logs to find the bug-fix someone mentioned last month. Honeybadger's built-in issue tracker keeps discussion central to each error, so that if it pops up again you'll be able to pick up right where you left off.
    Start free trial
    “Wow — Customers are blown away that I email them so quickly after an error.”
    Chris Patton, Founder of Punchpass.com
    Start free trial