Struct v1.0.0 Struct.Cast View Source
Module to make struct instance from provided params.
You can use it standalone, without defining struct, by providing types and params to make/3.
Link to this section Summary
Functions
Function to compose struct instance from params
Link to this section Types
Link to this section Functions
Function to compose struct instance from params:
defmodule User do
use Struct
structure do
field :name
end
end
iex> make(User, %{name: "john doe"})
{:ok, %User{name: "john doe"}}
Also you can use it as standalone complex type-coercion by providing types and params:
iex> make(%{name: {:string, []}}, %{"name" => "john doe"})
{:ok, %{name: "john doe"}}
iex> make(%{age: {:integer, [default: 18]}}, %{"age" => "42"})
{:ok, %{age: 42}}
iex> make(%{age: {:integer, [default: 18]}}, %{})
{:ok, %{age: 18}}
iex> types = %{title: {:string, []}, comments: {{:array, :string}, default: []}}
iex> make(types, %{title: "article", comments: ["awesome", "great!", "whoa!"]})
{:ok, %{title: "article", comments: ["awesome", "great!", "whoa!"]}}
Options:
make_map— return result as map instead of struct, defaults to false;empty_values— list of terms indicates empty values, defaults to [].
Example of empty_values:
iex> make(%{name: {:string, []}}, %{name: ""}, empty_values: [""])
{:error, %{name: :missing}}
iex> make(%{name: {:string, []}}, %{name: "john"}, empty_values: ["john"])
{:error, %{name: :missing}}