Inspired by this video, I used the 'with' macro in Elixir to cleanly refactor some code.
The problem I was trying to solve was that on module had a handle_event function that matched on the type of the first argument
def handle_event(%Events.TitleChanged{title: title}), do: ...But there were an increasing number of Event types. So this module was getting quite long and I wanted to split it into several modules that would each handle one group of events.
I split it into 3 sections, and made a default function for each of them return :not_handled.
def handle_event(_), do: :not_handled
Then I used `with` (as shown below), to keep trying until I find one that handles it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def handle_event(persisted_event) do | |
with :not_handled <- ActionFramework.handle_event(persisted_event), | |
:not_handled <- Action.handle_event(persisted_event), | |
:not_handled <- Comment.handle_event(persisted_event) do | |
:error | |
else | |
_ -> :ok | |
end | |
end |