Coercion v1.1.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 Types

Link to this type

output_type()

View Source
output_type() ::
  String.t()
  | integer()
  | boolean()
  | Date.t()
  | DateTime.t()
  | NaiveDateTime.t()
Link to this type

supported_type()

View Source
supported_type() ::
  :integer | :boolean | :string | :atom | :datetime | :naive_datetime

Link to this section Functions

Link to this function

coerce(value, atom)

View Source
coerce(any(), supported_type()) :: {:ok | :invalid | :blank, output_type()}

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"}
iex> :bellow
:bellow
iex> coerce("bellow", :atom)
{:ok, :bellow}
iex> coerce("   bellow  ", :atom)
{:ok, :bellow}

iex> coerce("2020-04-02", :date)
{:ok, ~D[2020-04-02]}
iex> coerce(:hello, :date)
{:invalid, nil}
iex> coerce("2020-04-02T12:00:01Z", :datetime)
{:ok, ~U[2020-04-02 12:00:01Z]}
iex> coerce("2020-04-02T12:00:01Z", :naive_datetime)
{:ok, ~N[2020-04-02 12:00:01]}