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

Define casting types

Link to this section 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.

Link to this section 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.

Link to this section 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.

Link to this section Functions

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

Casts the given input to the custom type.

basic-types

Basic types

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

example

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")}