MaxoAdapt
is a fork from https://github.com/IanLuites/adapter with updates / fixes.
Fast adapters with clear syntax and build-in safety.
- Fast (as fast as hardcoded
defdelegate
s) - Easy (define a behaviour and it takes care of everything else)
- Safe (will error if the implementation does not match the behaviour)
- Clean (clearly separated marked behaviour/delegate versus functions)
- Flexible (change implementation/adapter at runtime)
In addition to these basic qualities it is:
- Compatible and tested with releases (
distillery
,mix release
) - Documentation compatible (each stub copies the documentation of the
@callback
) - Spec / Dialyzer (each stub has a spec matching the
@callback
) - IDE (intelligent code completion / intellisense) compatible [stubs]
def deps do
[
{:maxo_adapt, "~> 0.1"}
]
end
defmodule SessionRepo do
use MaxoAdapt
# Define the adapter behaviour
behaviour do
@doc ~S"""
Lookup a sessions based on token.
"""
@callback get(token :: binary) :: {:ok, Session.t | nil} | {:error, atom}
end
# Add module functions outside the behaviour definition
# These can use the behaviour's callbacks like they exist as functions.
@spec get!(binary) :: Session.t | nil | no_return
def get!(token) do
case get(token) do
{:ok, result} -> result
{:error, reason} -> raise "SessionRepo: #{reason}"
end
end
end
# PostgreSQL implementation
defmodule SessionRepo.PostgreSQL do
@behaviour SessionRepo
@impl SessionRepo
def get(token), do: {:ok, {token, :psql}}
end
# Redis implementation
defmodule SessionRepo.Redis do
@behaviour SessionRepo
@impl SessionRepo
def get(token), do: {:ok, {token, :redis}}
end
# Now configure
SessionRepo.configure(SessionRepo.PostgreSQL)
# Runtime switching possible
SessionRepo.configure(SessionRepo.Redis)
The docs can be found at https://hexdocs.pm/maxo_adapt.
The lib is available as open source under the terms of the MIT License.