Hanami, Why?: Bits & Bobs
Welcome back to the Hanami, Why? series. In this issue, we will explore several smaller topics related to Hanami, despite them not being worthy of their own dedicated issues. These context pieces will help you better understand how Hanami operates. Ruby typically informs you of dependencies through require statements, but frameworks like Rails often autoload everything, leading to dependencies scattered throughout code.
Hanami addresses this through the Deps module, allowing you to declare dependencies upfront. Dependencies can be injected into any class, not just actions or repositories. Each file in the app/ directory gets registered under a key derived from its path. Hanami loads the code and provides a ready-to-use instance of the dependency.
When using Deps, ensure you call super in your initialize method to properly set dependencies. Hanami registers all files in app/ as components, even those not intended for injection. To exclude a class from being injected, use a magic comment at the top of the file. Components are memoized by default, instantiating once and reusing that instance.
To create a new instance each time, use another magic comment. The app/initializers directory in Rails, similar to Hanami's registration system, can lead to issues if dependencies are not loaded in the correct order. Hanami offers providers to register components, with three stages in their lifecycle: prepare, start, and stop. Providers are prepared and started before your application boots, akin to Rails' initializers.
Providers can register multiple components, and their behavior varies between development/test and production environments. Properly managing dependencies is crucial in Hanami applications to avoid unexpected behavior and ensure smooth operation.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.