Construct v1.0.1 Construct.Cast View Source
Module to make structure instance from provided params.
You can use it standalone, without defining structure, by providing types and params to make/3
.
Link to this section Summary
Functions
Function to compose structure instance from params
Link to this section Types
Link to this section Functions
Link to this function
make(struct_or_types, params, opts \\ [])
View Source
make(atom() | types(), map(), options()) :: {:ok, Construct.t() | map()} | {:error, term()}
Function to compose structure instance from params:
defmodule User do
use Construct
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 structure, 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}}