Hanami’s model domain is implemented in a way that separates the behavior that we want to express (entities) from the persistence layer (repositories and database). This design helps keep the interface of our objects small and therefore keeps them fast and reusable.

Basic Usage

To explain the basic usage, we use a PostgreSQL database.

As first step, we generate the model:

  1. $ bundle exec hanami generate model book
  2. create lib/bookshelf/entities/book.rb
  3. create lib/bookshelf/repositories/book_repository.rb
  4. create db/migrations/20170406230335_create_books.rb
  5. create spec/bookshelf/entities/book_spec.rb
  6. create spec/bookshelf/repositories/book_repository_spec.rb

The generator gives us an entity, a repository, a migration, and accompanying test files.

Entity

This is the generated entity:

  1. class Book < Hanami::Entity
  2. end

Repository

While this is the generated repository:

  1. class BookRepository < Hanami::Repository
  2. end

Let’s edit the migration with the following code:

  1. Hanami::Model.migration do
  2. change do
  3. create_table :books do
  4. primary_key :id
  5. column :title, String
  6. column :created_at, DateTime
  7. column :updated_at, DateTime
  8. end
  9. end
  10. end

Prepare the database

Now we need to prepare the database to use it:

  1. $ bundle exec hanami db prepare

We’re ready to use our repository:

  1. % bundle exec hanami console
  2. irb(main):001:0> book = BookRepository.new.create(title: "Hanami")
  3. => #<Book:0x007f95ccefb320 @attributes={:id=>1, :title=>"Hanami", :created_at=>2016-11-13 15:49:14 UTC, :updated_at=>2016-11-13 15:49:14 UTC}>

Learn more about repositories, entities, migrations, and database CLI commands.