View Source CastParams.Type behaviour (CastParams v0.0.5)

Define casting types

Summary

Types

Custom types are represented by user-defined modules.

Primitive types.

t()

A type, primitive or custom.

Callbacks

Casts the given input to the custom type.

Returns the type name for the custom type.

Functions

Casts the given input to the custom type.

Types

@type custom() :: atom()

Custom types are represented by user-defined modules.

@type primitive() :: base() | composite()

Primitive types.

@type t() :: primitive() | custom()

A type, primitive or custom.

Callbacks

@callback cast(value :: term()) ::
  {:ok, casted_value :: term()} | {:error, reason :: term()}

Casts the given input to the custom type.

@callback type() :: t()

Returns the type name for the custom type.

Functions

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

Casts the given input to the custom type.

Basic types

[:boolean, :integer, :string, :float, :decimal]

Example

iex> cast(:integer, "1.0")
{:ok, 1}
iex> cast(:integer, "")
{:error, :invalid}

iex> cast(:string, "some string")
{:ok, "some string"}
iex> cast(:string, nil)
{:ok, ""}

iex> cast(:integer, "1")
{:ok, 1}
iex> cast(:integer, "1.0")
{:ok, 1}

iex> cast(:boolean, "1")
{:ok, true}
iex> cast(:boolean, "0")
{:ok, false}

iex> cast(:float, "1")
{:ok, 1.0}
iex> cast(:float, "1.0")
{:ok, 1.0}

iex> cast(:decimal, "1.001")
{:ok, Decimal.new("1.001")}