Ecto.Type.cast/2

Parsed documentation:
View on GitHub
Casts a value to the given type.

`cast/2` is used by the finder queries and changesets
to cast outside values to specific types.

Note that nil can be cast to all primitive types as data
stores allow nil to be set on any column. Custom data types
may want to handle nil specially though.

    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.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(:uuid, "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
Suggestions:
Please help! Open an issue on GitHub if this assessment is incorrect.