By default, Hanami provides several sub-directories within your app directory for organizing and providing quick access to common objects such as actions, repositories, structs, views, and so forth. These are the foundational objects which make up a Hanami application. You can also add your own, custom, top-level directories as well. A few good examples are:
-
app/contracts: For global and reusable Dry Validation contracts. -
app/schemas: For global and reusable Dry Schema schemas. -
app/middleware: For custom middleware. -
app/providers: For sophisticated — and testable — providers beyond what you can do with Hanami’s primitiveconfig/providersas described in Hanami Containers. -
app/jobs: For global and reusable background processing as described in Hanami with Sidekiq.
While the above is nice, you don’t want to abuse your app directory by creating a ton of sub-directories for every business domain concept. This is where app/aspects comes into play because this gives you a top-level namespace in which to define — and organize — the business logic of your application. For instance, let’s say your application is an ePaper service which consists of models, firmware, and devices. Your structure might be:
/app/aspects/models /app/aspects/firmware /app/aspects/devices
The above provides several advantages:
-
Uses
aspectsas a short, but descriptive, top-level namespace for all of your business logic. -
The
app/aspectsdirectory is, alphabetically, near Hanami’s defaultapp/actionsandapp/assetsdirectories which is one of the first directories you’ll see when navigation through your objects. -
The namespace is short and simple to type. Example:
Demo::Aspects::Firmware::Creator. Same goes for dependency injection:aspects.firmware.creator. -
Allows you to keep your business logic well organized while avoiding unnecessary top-level pollution of your
appdirectory.
💡 Keep in mind that, even though we are discussing the structure of a Hanami application, this concept works extremely well with any web application framework. You are definitely not limited to only using this namespace for Hanami applications.
Let’s explore what you can do with this simple, yet powerful, namespace.
Patterns
You are free to use whatever pattern you see fit for architecting your business logic. That said, the following patterns are quite powerful and highly recommended:
-
Command Pattern: By default, this is your go to pattern which allows you to quickly interchange classes, methods, lambdas, and procs as functional objects. This is the foundational building block to applying the more advanced Railway Pattern to building fault tolerant and robust functional pipelines.
-
Functions: Modules are the fastest and most memory performant objects within Ruby. This is where you can use the Functionable gem to namespace your reusable functions.
-
Whole Value Objects: While often overlooked, whole value objects such as Data, Structs, and Wholeable give you multiple ways in which to encapsulate raw data as whole value objects with direct access to the attributes you need.
Next, we’ll explore a few examples of the above.
Examples
Commands
It’s common, with web applications, to need a User Interface (UI) and an Application Programmable Interface (API). You might also need a Command Line Interface (CLI) too. You definitely don’t want to duplicate this logic, across multiple locations, because this leads to a maintenance nightmare and inconsistent behavior across different interfaces. The solution is to encapsulate and reuse as commands. Here are a few examples:
-
Creators: Creates a new record.
-
Updaters/Upserters: Creates a new record if not found or updates an existing record if found.
-
Deleters: Deletes an existing record.
-
Cloners: Clones of existing record in order to make an altered version of the original.
-
Synchronizers: Encapsulates the logic for synchronizing records between one or more external services. You often need these when sharing information across systems.
-
Importers/Exporters: Imports data into your system or exports data out of of your system for sharing across multiple systems.
Using our ePaper application example, from before, the namespaced directory becomes:
/app/aspects/models/creator.rb /app/aspects/models/deleter.rb /app/aspects/firmware/creator.rb /app/aspects/firmware/deleter.rb /app/aspects/devices/creator.rb /app/aspects/devices/deleter.rb
While only showing a few commands, you can see how this structure unfolds. This provides the following benefits:
-
Quick access to similar objects by using your favorite editor to fuzzy type and immediately jump to the aspect of your choice.
-
Leads by example since anyone on your team can look at an existing commands when needing to implement new business logic. Even better, they can see how the commands are adapted to suit the UI, API, and/or CLI.
-
Avoids the Reduntant Naming antipattern where the namespace is unnecessarily duplicated within the object. For example, avoiding these kinds of object names:
Firmware::CreateFirmware.
All of the above adheres to the Command Pattern and Railway Pattern which makes them quick to message (i.e. creator.call) while remaining fault tolerant since they’ll answer a monad for which you can use Pattern Matching to render a success or failure. Example:
require "core"
module Demo
module Aspects
module Firmware
# Creates new firmware with attachment and associations.
class Creator
include Deps[repository: "repositories.firmware"]
include Dry::Monads[:result]
def call attributes, io, validator:
validator.call(attributes).to_monad.fmap { create it.to_h, io }
end
private
def create attributes, io
firmware = repository.create attributes.fetch(:firmware)
return Failure("Unable to create firmware.") unless firmware
repository.update_with_models firmware.id, Core::EMPTY_HASH, attributes[:model_ids]
repository.replace_attachment firmware, firmware.version, io
end
end
end
end
end
The above encapsulates all of the logic for creating a new firmware record which performs the following steps:
-
Uses Dry Validation to validate the attributes are of the right structure, type, and use the required (or optional) keys and values. Even better, flexibility is maximized because you can supply a different validator depending on specific needs of interface used.
-
If successful, creates the firmware.
-
If successful, updates associated models.
-
If successful, replaces the attachment with an updated firmware binary.
As you can see, the lines are short, simply, and easy to read. Due to Hanami’s native use of Dependency Injection Containers, you can quickly inject the same dependency for reuse across your application’s multiple interfaces. That’s a lot of power for only a few lines of code!
Functions
As detailed in Ruby Modules, they are a great way to namespace related functions especially when using the Functionable gem to ensure your module of functions remain purely functional. Here’s an example of a collection of functions which parse various data formats (i.e. CSV, JSON, Text, and XML) into a common data format, hash, for further processing:
# auto_register: false
require "core"
require "csv"
require "dry/monads"
require "functionable"
require "json"
require "nori"
require "refinements/string"
module Demo
module Aspects
# Sources supported data types into a hash for further processing.
module Source
extend Dry::Monads[:result]
extend Functionable
using Refinements::String
def from_csv content
Success ::CSV.parse(String(content), headers: true).each.map(&:to_h)
rescue ::CSV::MalformedCSVError => error
Failure error.message
end
def from_json content
content = String(content).empty? ? Core::EMPTY_ARRAY : JSON(content)
Success content
rescue ::JSON::ParserError => error
Failure "#{error.message.up}."
end
def from_text content
Success String(content).split
rescue ArgumentError => error
Failure "#{error.message.up}."
end
def from_xml content, nori: Nori.new(parser: :rexml)
content = nori.parse String(content)
Success content.empty? ? Core::EMPTY_ARRAY : content
rescue REXML::ParseException => error
Failure error.message
end
end
end
end
To use, you only need to message the function of the data format you want to convert. Example:
Aspects::Source.from_csv # Answers a hash.
Aspects::Source.from_json # Answers a hash.
Aspects::Source.from_text # Answers a hash.
Aspects::Source.from_xml # Answers a hash.
Functions, like these, are perfect when you dealing with little to no state by avoiding a class and using a module instead.
Whole Value Objects
Sometimes, you don’t need a command or function but only a whole value object that encapsulate a set of attributes for quick access to the data you need. You might also be working with an API that is so poorly designed, which abuses HTTP headers, that you also need your whole value object to map the incoming HTTP headers to reasonable attribute names. Example:
require "refinements/hash"
module Demo
module Aspects
module Firmware
module Headers
KEY_MAP = {
HTTP_ACCESS_TOKEN: :api_key,
HTTP_FW_VERSION: :firmware_version,
HTTP_HEIGHT: :height,
HTTP_ID: :mac_address,
HTTP_MODEL: :model_name,
HTTP_PERCENT_CHARGED: :battery_charge,
HTTP_REFRESH_RATE: :refresh_rate,
HTTP_RSSI: :wifi_signal,
HTTP_SENSORS: :sensors,
HTTP_SPECIAL_FUNCTION: :action,
HTTP_UPDATE_SOURCE: :wake_reason,
HTTP_USB_CONNECTED: :charging,
HTTP_WIDTH: :width,
HTTP_WIFI_BAND: :wifi_band
}.freeze
# Models the HTTP headers for quick access to attributes.
Model = Data.define(*KEY_MAP.values) do
using Refinements::Hash
def self.for headers, key_map: KEY_MAP
headers.transform_keys(key_map).then { new(**it) }
end
def initialize(**)
super(**members.to_h { [it, nil] }, **)
end
end
end
end
end
end
With the above we have a Data object which represents the HTTP response headers including a handy .for method which transforms raw values into attributes we can work with using the KEY_MAP as the index. You could have a separate object for handling the transform but often it’s nice to keep this together by using the .for method to show how the external data is being transformed for internal use without infecting your system’s design.
Guidelines
In addition to everything discussed so far, there are a few guidelines worth keeping in mind when organizing your business logic:
-
Keep your
appdirectory clean by organizing business logic withinapp/aspects. Only in situations where a global namespace would benefit your entire application should you add a top-levelappdirectory. -
Use your
libdirectory for common objects that are not specific to your application. You’ll want to use sub-directories to namespace your objects as done forapp/aspects. Any object that ends up here is always a good candidate for turning into a gem in the future. -
Avoid Dry Operation for your commands as this is Hanami’s default solution for leveraging the Railway Pattern to build fault tolerant pipelines but the Domain Specific Language (DSL) is ugly, cumbersome, and too generic. There is also talk of incorporating contracts which would carry over the same disadvantages of contract use as described with Hanami Actions. Instead, stick with Dry Monads or level up to the Pipeable gem which also has it’s own DSL but with less typing and more customization of steps.
-
Avoid naming any of this as service objects. Services are legit third-party interactions, usually requiring APIs, and should definitely not be used as a generic bucket to dump all of your business logic in. More importantly, people often think all services must adhere to the same pattern which is extremely limiting. With aspects, now you can namespace by business logic using any pattern that provides the best solution.
Conclusion
You’ve learned what aspects are, why they are important, and how to use them. You’ve also learned, and seen examples, of a few patterns you can use as aspects of your application. Even better, none of these learnings are restricted to Hanami as you can apply all of the above to any application in order to keep your business logic well organized. Enjoy!