From Rails to Hanami: Models
This article is the first of a series called "From Rails to Hanami" and it will show you how you can make a ToDo List with Hanami and compare it to the way you would do using Rails.
What is Hanami?
Hanami is a MVC web framework for Ruby that prioritize the use of plain objects over magical classes with too much responsibility.
Let's jump into some code!
Let's say you want a Task model with a scope for the high priority tasks. In Rails, you would do something as the code below
In Rails the models live under the app/models folder while in Hanami, they live under lib/entities and lib/repositories folders.
An entity is a model domain object. It holds the models attributes, but it doesn't deal with the persistence layer. So our first entity will look like
And you can instantiate new entities the same way you're used to do with Rails
A repository is responsible for dealing with the persistence of our entities. So the first version of our task repository will be as simple as that:
To create a Task on the database, you can pass an entity instance as a parameter to the repository or use the attributes hash.
The repository offers
clear methods as you would expect on Rails models, and works just like a charm.
Queries are private to the repository context, which means that methods like
order are only available for methods inside the repository. This is good so the caller doesn't know how the queries or the internals mechanisms works. You may think this is unnecessary, but when you need to use queries, you won't bloat your models with a lot of scopes and you will have your queries in the right place, as in the example below:
The tasks method is created by Hanami behind the scenes and is base relation where you will do your queries.
To keep track of when a record is created or updated, you can add
updated_at columns and your repository will make sure their values are updated.
See how easy it is? At first you will have more lines of code but in the future you'll have much more control of your project and your code will be more reusable and easier to test.
If you enjoyed this article, recommend it and follow me to stay tuned about the next part where we will talk about controllers!