Getting Started with Hanami 2
Hanami 2 is a modern Ruby framework that emphasizes simplicity, small memory footprint, and clean architecture. Unlike Ruby on Rails, Hanami takes a minimalist approach—building only what you need, when you need it. This guide walks you through installing Hanami 2 and creating your first application.
Why Choose Hanami?
Before we dive in, let’s understand what makes Hanami 2 special:
- Lightweight: Hanami ships with a fraction of Rails’ dependencies, giving you a faster, leaner framework
- Flexible: No forced conventions—organize your code your way, not the framework’s way
- Fast: Smaller footprint means faster boot times and lower memory usage, perfect for microservices
- Modern: Built for Ruby 3.2+ with native type annotations support and forward-thinking design
If you’re coming from Rails, Hanami might feel like a breath of fresh air—same Ruby goodness, but with more control over your application’s structure. Many developers find Hanami strikes a nice balance between Rails’ convenience and Sinatra’s simplicity.
Installing Hanami 2
Hanami provides a convenient installer that sets up everything for you. Open your terminal and run:
gem install hanami
This installs the Hanami CLI and its dependencies. The installer handles all the heavy lifting, setting up the correct directory structure and configuration files. Once installed, verify the version:
hanami --version
You should see output similar to 2.0.0 or higher. If you see an error, make sure you have Ruby 3.2 or later installed—Hanami 2 requires a recent Ruby version.
Creating Your First Hanami App
Now let’s create a new Hanami application. This is the moment you’ve been waiting for:
hanami new myapp
This command creates a new directory called myapp with the following structure:
myapp/
├── app/
│ ├── actions/ # Request handlers
│ ├── views/ # View templates
│ └── models/ # Domain logic
├── config/
│ └── routes.rb # Routing configuration
├── db/ # Database migrations
└── spec/ # Test files
Navigate into your new project:
cd myapp
You’ll notice the structure is cleaner than what you might be used to from Rails. There’s no app/controllers, app/helpers, or app/assets directories by default—you add what you need, when you need it.
Starting the Development Server
Hanami includes a development server powered by Puma. Starting it is straightforward:
hanami server
By default, your app runs at http://localhost:3000. Open that URL in your browser—you should see the default Hanami welcome page. The server automatically reloads your code as you make changes, just like you’re used to with Rails.
One thing you’ll notice immediately is how fast the server starts. Because Hanami doesn’t load unnecessary dependencies, your app boots in seconds rather than the minutes you might expect from a larger framework.
Understanding Hanami’s Architecture
Hanami follows a slightly different architecture than Rails. Understanding these differences will help you write better Hanami applications. Let’s break down the key components:
Actions
Actions handle HTTP requests. Each action is a class with a call method—this is similar to Rails controllers but more explicit:
# app/actions/books/index.rb
module Books
module Index
class Action < Hanami::Action
def call(params)
# Handle the request
end
end
end
end
Notice how each action is its own class. This makes testing easier and keeps your code modular. Unlike Rails where controllers can become massive, Hanami encourages small, focused action classes. Views handle responses. They receive data from actions and render templates. In Hanami, views are completely separate from actions—this separation of concerns is intentional:
# app/views/books/index.rb
module Books
module Index
class View < Hanami::View
end
end
end
Views in Hanami can render multiple formats from the same view class—HTML, JSON, XML, and more. This makes building APIs straightforward.
Models
Models contain your business logic. In Hanami 2, you can use any persistence layer you prefer. ROM (Ruby Object Mapper) is the default, but you’re not locked in:
# app/models/book.rb
class Book < Hanami::Model::Entity
end
Hanami’s approach to models is refreshingly simple—entities are plain Ruby objects that represent your domain concepts.
Creating Your First Route
Routes define how URLs map to actions. Open config/routes.rb to see the default configuration:
# config/routes.rb
Hanami.configure do
root to: "home#index"
get "/books", to: "books#index"
get "/books/:id", to: "books#show"
end
The routing DSL is clean and expressive. After saving, the routes are automatically available—no restart needed during development. This is one of those quality-of-life features you’ll appreciate after using it.
Creating Your First Action
Let’s create a simple “Hello World” action to see how everything connects. First, create the actions directory structure:
mkdir -p app/actions/greetings
Now create the action file:
# app/actions/greetings/hello.rb
module Greetings
class Hello < Hanami::Action
def call(params)
self.body = "Hello, Hanami!"
end
end
end
Add a route for it:
get "/hello", to: "greetings#hello"
Visit http://localhost:3000/hello—you should see “Hello, Hanami!” in your browser.
Using Parameters
Actions can accept parameters from the URL. Let’s enhance our hello action to use query parameters:
# app/actions/greetings/hello.rb
module Greetings
class Hello < Hanami::Action
def call(params)
name = params[:name] || "World"
self.body = "Hello, #{name}!"
end
end
end
Now visit http://localhost:3000/hello?name=Ludwig—you’ll see “Hello, Ludwig!” displayed. The params object gives you clean access to all types of parameters—query strings, route parameters, and request body data.
When to Use Hanami
Hanami excels in several scenarios:
- Microservices: Its small footprint makes it ideal for small services
- API-first applications: Building JSON APIs is straightforward
- Learning Ruby web development: The simpler architecture is easier to understand
- Performance-critical applications: Less memory and faster boot times matter
However, if you need the full-stack features of Rails or are working with a team that knows Rails well, the migration cost might not be worth it.
What’s Next?
You’ve just created your first Hanami 2 application! Here’s what to explore next:
- Actions and Views: Learn how to render HTML, JSON, and other formats
- Database Persistence: Set up ROM for working with databases
- Slices: Organize larger applications into modular slices
The next tutorial in this series covers Actions and Views in Hanami, where you’ll learn how to build complete request-response cycles with proper data flow between layers.
Happy coding!