Commandex.Type behaviour (Commandex v0.6.0)

Copy Markdown View Source

Behaviour for custom Commandex types.

A type module implements the cast/1 callback, which converts a raw input value into the value that the command uses.

Example

defmodule MyApp.Types.Color do
  @behaviour Commandex.Type

  @type t :: %{r: integer(), g: integer(), b: integer(), a: float()}

  @impl true
  def cast(%{r: r, g: g, b: b, a: a} = color)
      when is_integer(r) and is_integer(g) and is_integer(b) and is_float(a) do
    {:ok, color}
  end

  def cast(_), do: :error
end

Use the module as the type of a param:

param :color, MyApp.Types.Color

The t() type

A type module must define a t() type. The typespec of the command struct refers to it. The :color param above has the spec MyApp.Types.Color.t() | nil.

If the module does not define t(), the command still compiles and runs. Dialyzer then reports an unknown type.

Types with options

A type can take options from the param line. A type with options implements init/1 and cast/2, and does not implement cast/1.

init/1 runs at compile time. It gets the options from the param line and returns the params of the type. cast/2 gets the raw input value and those params.

This example is an enum type for an API that sends "PENDING_REVIEW" when the command needs :pending_review:

defmodule MyApp.Types.Enum do
  @behaviour Commandex.Type

  @type t :: atom()

  @impl true
  def init(opts) do
    values = Keyword.fetch!(opts, :values)
    from_api = Map.new(values, &{String.upcase(Atom.to_string(&1)), &1})
    from_atom = Map.new(values, &{&1, &1})

    Map.merge(from_api, from_atom)
  end

  @impl true
  def cast(value, lookup), do: Map.fetch(lookup, value)
end

Each param gives its own options:

param :status, MyApp.Types.Enum, values: [:active, :pending_review]
param :sort, MyApp.Types.Enum, values: [:asc, :desc], default: :asc

Obey these rules when you write a type with options:

  • init/1 gets every option from the param line. This includes :default and :required.
  • Raise an error in init/1 if an option is not valid. The error then shows at compile time.
  • Return plain data from init/1, such as a map or a list. The command struct stores the value, so it cannot contain an anonymous function.

Nil values

A type module does not get a nil value. Commandex.Type.cast/2 returns {:ok, nil} for nil before it calls the module.

Summary

Types

t()

A parameter type.

Callbacks

Casts a raw input value.

Casts a raw input value with the params from init/1.

Converts the options from the param line into the params of the type.

Functions

Casts a value to the given type.

Types

t()

@type t() ::
  :any
  | :binary
  | :boolean
  | :date
  | :decimal
  | :float
  | :integer
  | :map
  | :naive_datetime
  | :naive_datetime_usec
  | :string
  | :time
  | :time_usec
  | :utc_datetime
  | :utc_datetime_usec
  | {:array, t()}
  | {:map, t()}
  | {:parameterized, {module(), params :: term()}}
  | module()

A parameter type.

A type is a built-in atom, an {:array, type} or {:map, type} tuple, or a module that implements this behaviour. A module with options is stored as {:parameterized, {module, params}}.

Callbacks

cast(value)

(optional)
@callback cast(value :: term()) :: {:ok, term()} | :error | {:error, keyword()}

Casts a raw input value.

Return {:ok, value} if the cast succeeds and :error if it fails. {:error, keyword} is also a failure.

cast(value, params)

(optional)
@callback cast(value :: term(), params :: term()) ::
  {:ok, term()} | :error | {:error, keyword()}

Casts a raw input value with the params from init/1.

The return values are the same as for cast/1.

init(opts)

(optional)
@callback init(opts :: keyword()) :: term()

Converts the options from the param line into the params of the type.

This callback runs at compile time.

Functions

cast(module, value)

@spec cast(t(), term()) :: {:ok, term()} | :error

Casts a value to the given type.

Returns {:ok, cast_value} if the cast succeeds and :error if it fails. nil always returns {:ok, nil}, for every type.

Examples

iex> Commandex.Type.cast(:integer, "42")
{:ok, 42}

iex> Commandex.Type.cast(:integer, 4.2)
:error

iex> Commandex.Type.cast({:array, :boolean}, ["true", "0"])
{:ok, [true, false]}

iex> Commandex.Type.cast(:string, nil)
{:ok, nil}