View Source DispatchEx (DispatchEx v0.1.2)
Sets up a module for a protocol dispatch or a concrete implementation.
example
Example
defmodule PolymorphicCommand do
use Dispatch, :protocol
@callback cast(term()) :: {:ok, term()} | {:error, reason :: term()}
# this becoms the default implementation
def cast(_), do: raise ArgumentError, "unable to cast command description"
end
defmodule ReadCommand do
use Dispatch, for: PolymorphicCommand
def cast(%{type: read, key: k}), do: {:read, k}
end
defmodule WriteCommand do
use Dispatch, for: PolymorphicCommand
def cast(%{type: :write, key: k, value: v}), do: {:write, k, v}
end
{:read, 1} = PolymorphicCommand.cast(%{type: :read, key: 1})
{:write, 1, :x} = PolymorphicCommand.cast(%{type: :write, key: 1, value: :x})
````