Coercion v1.0.0 Coercion View Source

Rigorous coercion of untrusted values to native primitive types

Link to this section Summary

Functions

Coerce and validate a value to the given type

Link to this section Functions

Link to this function coerce(value, atom) View Source
coerce(any, :integer | :boolean | :string) :: {:ok | :invalid | :blank, String.t | integer | Boolean.t}

Coerce and validate a value to the given type.

Examples

iex> import Coercion # For demo purposes
Coercion

iex> coerce(" 20 ", :integer)
{:ok, 20}
iex> coerce("  x", :integer)
{:invalid, 0}

iex> coerce(" TRue ", :boolean)
{:ok, true}
iex> coerce(" T ", :boolean)
{:ok, true}
iex> coerce(" y ", :boolean)
{:ok, true}
iex> coerce(" Yes ", :boolean)
{:ok, true}
iex> coerce(" 1 ", :boolean)
{:ok, true}
iex> coerce(" TRu ", :boolean)
{:invalid, false}
iex> coerce(" F ", :boolean)
{:ok, false}
iex> coerce(" N ", :boolean)
{:ok, false}
iex> coerce(" 0 ", :boolean)
{:ok, false}

iex> coerce(" hello ", :string)
{:ok, "hello"}
iex> coerce("  ", :string)
{:blank, ""}
iex> coerce(true, :string)
{:ok, "true"}
iex> coerce(10.5, :string)
{:ok, "10.5"}