I love Elixir and the implementation of protocols. Here is an example of how you
can implement a protocol for a given data type/structure.
What this example shows:
1st: There is a protocol named Usecase. It declares all functions of the
implementation of the protocol Usecase needs.
So, you can execute it like so:
Define a module for your use case
Now you can use it like so
2nd: The ‘magic’ is stupid simple
It’s all about the structure %YourUsecase{} which will be injected by the
line use Clean and is defined there as
request holds the parameter/arguments passed in Usecase.request(…..).
errors is just a list where errors being added to during execution.
result holds whatever your execute(...) function returns. Usually, it is
an ok/error tuple like {:ok, valid_result} or {:error, reason}.
halt is either false or true. It will initialize with false, but any
step previous to execute can set it to false. Thus the execution function
will not be executed.
client defaults to :system but is supposed to hold the client-metadata for
which the use case should execute. In web apps, this may be the current user,
the remote_ip, the user-agent,…
By now, there is no validate function. But you simply can implement it and
call it just before execute. You can add this as homework ;-)
Full Example
No need to compile this file. Just execute it with