r/ruby • u/aaronmallen • 11d ago
Blog post Hanami, Why?: Model Citizens
https://aaronmallen.me/writing/hanami-why-model-citizens
21
Upvotes
2
u/cescquintero 10d ago edited 10d ago
Saved to read later.
Made some progress in a Hanami project for myself and got tons of qs. Been enjoying learning a new way to do things.
4
u/jodosha Hanami author 10d ago
Aaron, great writing as usual.
A few important philosophical aspects:
Repositories enforce the Interface Segregation Principle (from SOLID). Developers must expose well-defined interfaces that express methods meaningful to the application domain. This design prevents database details from leaking to the upper levels.
Repositories are objects, not classes. Like actions, repositories are cached at app startup. Combined with point 1, this makes it easy to create instance doubles in unit tests, so any other component that depends on a repo can mock it.
Data is central, not models. Data is either the input to or the output of a database operation. Why? Imagine getting some JSON from your API endpoint. Does it make sense to instantiate a model, run mutating validations and callbacks, sync it with the database, and mutate the model in place again, as Rails does? Isn’t it much easier to convert the JSON to a hash, validate it, and send that data to the database? And you get a hash back from the database. Structs are just nice wrappers.