Construct v2.1.4 Construct.Type behaviour View Source
Type-coercion module, originally copied and modified from Ecto.Type and behaviour to implement your own types.
Defining custom types
defmodule CustomType do
@behaviour Construct.Type
def cast(value) do
{:ok, value}
end
end
Link to this section Summary
Functions
Behaves like cast/3
, but without options provided to nested types
Casts a value to the given type
Checks if we have a primitive type
Callbacks
Casts the given input to the custom type
Link to this section Types
Link to this section Functions
Behaves like cast/3
, but without options provided to nested types.
Casts a value to the given type.
iex> cast(:any, "whatever")
{:ok, "whatever"}
iex> cast(:any, nil)
{:ok, nil}
iex> cast(:string, nil)
:error
iex> cast(:integer, 1)
{:ok, 1}
iex> cast(:integer, "1")
{:ok, 1}
iex> cast(:integer, "1.0")
:error
iex> cast(:float, 1.0)
{:ok, 1.0}
iex> cast(:float, 1)
{:ok, 1.0}
iex> cast(:float, "1")
{:ok, 1.0}
iex> cast(:float, "1.0")
{:ok, 1.0}
iex> cast(:float, "1-foo")
:error
iex> cast(:boolean, true)
{:ok, true}
iex> cast(:boolean, false)
{:ok, false}
iex> cast(:boolean, "1")
{:ok, true}
iex> cast(:boolean, "0")
{:ok, false}
iex> cast(:boolean, "whatever")
:error
iex> cast(:string, "beef")
{:ok, "beef"}
iex> cast(:binary, "beef")
{:ok, "beef"}
iex> cast(:decimal, Decimal.new(1.0))
{:ok, Decimal.new(1.0)}
iex> cast(:decimal, Decimal.new("1.0"))
{:ok, Decimal.new(1.0)}
iex> cast(:decimal, 1.0)
{:ok, Decimal.new(1.0)}
iex> cast(:decimal, "1.0")
{:ok, Decimal.new(1.0)}
iex> cast({:array, :integer}, [1, 2, 3])
{:ok, [1, 2, 3]}
iex> cast({:array, :integer}, ["1", "2", "3"])
{:ok, [1, 2, 3]}
iex> cast({:array, :string}, [1, 2, 3])
:error
iex> cast(:string, [1, 2, 3])
:error
Checks if we have a primitive type.
iex> primitive?(:string)
true
iex> primitive?(Another)
false
iex> primitive?({:array, :string})
true
iex> primitive?({:array, Another})
true
iex> primitive?([Another, {:array, :integer}])
false
Link to this section Callbacks
Casts the given input to the custom type.