struct v0.1.2 Struct.Type behaviour

Summary

Functions

Checks if the given atom can be used as base type

Casts a value to the given type

Checks if the given atom can be used as composite type

Checks if we have a primitive type

Callbacks

Casts the given input to the custom type

Types

custom :: atom
primitive :: base | composite

Functions

base?(atom)

Specs

base?(atom) :: boolean

Checks if the given atom can be used as base type.

iex> base?(:string)
true
iex> base?(:array)
false
iex> base?(Custom)
false
cast(types, term)

Specs

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

Casts a value to the given type.

iex> cast(:any, "whatever")
{:ok, "whatever"}

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

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({: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
composite?(atom)

Specs

composite?(atom) :: boolean

Checks if the given atom can be used as composite type.

iex> composite?(:array)
true
iex> composite?(:string)
false
primitive?(base)

Specs

primitive?(t) :: boolean

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

Callbacks

cast(term)

Specs

cast(term) :: {:ok, term} | :error

Casts the given input to the custom type.