Hanami 2.0 to 2.2: What’s New and Why It Matters for Web Developers 🚀

If you’re a Ruby fan or looking for a web framework that combines power and simplicity, Hanami is worth checking out. Known for its clean, modular design, it’s perfect for developers who value elegant code and efficient workflows. With several impressive updates from 2.0 to 2.2, Hanami keeps raising the bar for web development.

This post dives into what’s new, how these updates benefit developers, and, most importantly, how you can put them into action. Get ready for some hands-on examples along the way!

Why Hanami Stands Out

Before we explore the latest features, here’s a quick refresher on why Hanami is special. Unlike monolithic frameworks, it takes a modular approach, letting you pick and choose the pieces you need. It’s lightweight, scalable, and harmonizes beautifully with Ruby gems like dry-rb and ROM.

Now, combine this philosophy with updates aimed at performance boosts and developer joy, and you’ve got a standout framework. 🔥

Hanami 2.0: A Turning Point

Hanami 2.0 introduced a bold new architecture, emphasizing simplicity and modularity while keeping things developer-friendly.

Decoupled Components

Hanami’s design means its individual components—like Hanami::Action or Hanami::View—can work independently. This is a game-changer for teams building microservices or apps with specific needs.

Example: Imagine building a lightweight API without all the bells and whistles of a full stack. You can use Hanami::Router to handle routing while keeping everything else minimal:

Routing Example:

Here’s a simple API that maps HTTP actions to methods:

require 'hanami-router'

router = Hanami::Router.new do
  get '/users', to: ->(env) { [200, {}, ["Here’s your user data!"]] }
  post '/users', to: ->(env) { [201, {}, ["User created successfully!"]] }
end

Rack::Handler::WEBrick.run(router, Port: 9292)

This keeps your code focused while leveraging Hanami’s flexibility.

Integration with Dry-rb and ROM

Hanami 2.0’s adoption of the dry-rb family of libraries and ROM makes data modeling and validation effortless. Whether it’s validating form inputs or manipulating database entries, these tools simplify your codebase.

Dry Validation Example:

Here’s how you’d validate user data for a signup form:

require 'dry-schema'

UserSchema = Dry::Schema.Params do
  required(:username).filled(:string, min_size?: 3)
  required(:email).filled(:string, format?: /@/)
  required(:password).filled(:string, min_size?: 8)
end

input = { username: 'demo', email: 'demo@example.com', password: '12345678' }
result = UserSchema.call(input)

if result.success?
  puts "Input is valid!"
else
  puts result.errors.to_h # Outputs any validation errors
end

This compact, reusable code reduces boilerplate while catching issues early.

Hanami 2.1: Leveling Up

Hanami 2.1 elevated the framework’s core by introducing performance improvements and new tools for smoother development.

Enhanced Request Lifecycle

Handling requests smoothly is crucial, and Hanami 2.1 refined the process further. Middleware can now interact with requests more efficiently, letting you inject logic at just the right time.

Custom Middleware Example:

Here’s middleware that adds a timestamp to each request:

class RequestTimeLogger
  def initialize(app)
    @app = app
  end

  def call(env)
    puts "Request started at #{Time.now}"
    @app.call(env) # Pass the request along
  end
end

router = Hanami::Router.new do
  get '/', to: ->(env) { [200, {}, ["Welcome!"]] }
end

Rack::Handler::WEBrick.run RequestTimeLogger.new(router), Port: 9292

Clean, practical, and easy to integrate.

Smarter Views

Rendering templates is even easier with the updated Hanami::View object. This ensures your templates stay focused on presentation while logic stays in the view object.

View Object Example:

Here’s how you’d expose data to a template:

# view.rb
class ArticleView
  include Hanami::View

  expose :title
  expose :body
end

# template.html.erb
<h1><%= title %></h1>
<p><%= body %></p>

Keep templates lean, testable, and flexible!

Hanami 2.2: Breaking New Ground

With version 2.2, Hanami builds on its strong foundation with features that are especially exciting for real-time applications and testing.

Websockets Built-In

Yes, you read that right—Hanami 2.2 makes it easy to enable real-time communication via websockets. This is perfect for apps that need live updates, like chats or dashboards.

Websocket Implementation Example:

Here’s a basic websocket setup for a live chat feature:

class ChatChannel < Hanami::Websocket
  def on_connect(client)
    broadcast "User #{client.id} connected!"
  end

  def on_message(data, client)
    broadcast "#{client.id}: #{data}"
  end
end

No need for external dependencies. Just declare your channel logic and go!

Testing Utilities

Testing in Hanami has always been robust, but 2.2 makes it even better by expanding helpers for mocking and stubbing.

Mock Example:

Here’s a unit test that uses stubbing for a repository method:

RSpec.describe CreateUser do
  it "creates a user successfully" do
    repo = instance_double(UserRepository)
    allow(repo).to receive(:create).and_return(User.new(id: 1, name: "Test User"))

    service = CreateUser.new(repo)
    result = service.call(name: "Test User")

    expect(result.id).to eq(1)
  end
end

The result? Cleaner specs and a lot less setup time.

Improved Active Record Compatibility

For teams transitioning from Rails, Hanami 2.2 makes it easier to work with Active Record. Use Active Record for database management while enjoying Hanami’s other features.

AR Integration Example:

You can map Active Record models neatly into your Hanami app without requiring major rewrites:

class User < ApplicationRecord
end

class UsersController
  def index
    @users = User.all
  end
end

Flexibility is at your fingertips!

Why Developers Should Switch to Hanami

Hanami offers substantial benefits for those who care about clean architecture and developer joy. The modular design is perfect for building microservices or scaling projects efficiently. Plus, its integration with Ruby gems opens the door for better code practices.

If you’ve been stuck in the Rails world, Hanami is a breath of fresh air. It’s lighter, faster, and increasingly capable of meeting modern development needs—like real-time features or advanced data modeling.

Key Takeaways

  • Use decoupled components for lightweight, tailor-made applications.
  • Build websockets with ease for real-time functionalities.
  • Validate data better and faster with dry-rb integration.
  • Write robust, modern tests using the improved testing utilities.

Wrapping Up

Hanami 2.0 to 2.2 is everything you want in a web framework—clean architecture, modern tools, and practical features. If you haven’t tried it yet, now’s the time to jump in. It could very well transform the way you build applications.

Happy coding! 🌟

Tags:

Categories:

Updated:

Have comments or want to discuss this topic?

Send an email to ~bounga/public-inbox@lists.sr.ht