Hanami is a modern full-stack Ruby web framework that offers developer freedom by not imposing too many default assumptions, unlike Rails. The framework is known for its speed, low memory footprint, and focus on minimalism. With strict abstractions, Hanami can be a viable alternative to Rails for building applications like APIs and micro-services. In this tutorial, we will explore the structure and features of Hanami by building a simple blog application. Let’s get started.
Prerequisites:
– Ruby 3.0+ installed
– Local installation of Postgresql
Installing Hanami and generating a new application:
1. Install Hanami by running the command:
2. Generate a new Hanami app with the command:
3. This will create an app directory structure similar to Rails, with directories like app, lib, and config for organizing your code and configurations.
Note: Hanami version 2.0 does not include the Hanami view integration, so you will need to add the Hanami view gem to your Gemfile and run bundle install.
The app we’ll be building:
We’ll be building a simple blog app to showcase Hanami’s internals and strengths. You can find the source code for the completed app here.
Adding persistence to a Hanami app:
Since Hanami 2.1 will include a natively integrated persistence library, we’ll use the Ruby Object Mapper (ROM) library for the persistence layer in our blog app. Follow these steps to add persistence:
1. Install the ROM library by adding the gems to your Gemfile and running bundle install.
2. Create a Postgresql database and configure the database settings in the app.
3. Add a persistence provider in the config/providers/persistence.rb file to manage database connections.
4. Define the database connection string in the app’s settings file and set up the .env file with the database URL.
5. Create and run the first migration manually using rake tasks to set up the posts table in the database.
Next, we’ll build a relation to interact with the posts table and set up a repository with CRUD methods for accessing data. The relation defines how data is read and written to the database, while the repository provides convenient methods for interacting with the posts data.
By following these steps, you’ll have a working blog application in Hanami with persistence and data access capabilities. Feel free to explore the ROM library and Hanami’s documentation for more advanced features and functionalities.
Source link