Construct v2.1.4 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 type options() View Source
options() :: [make_map: boolean(), empty_values: [term()]]
Link to this type types() View Source
types() :: %{required(atom()) => type()}

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"}}

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(%{name: :string}, %{"name" => "john doe"})
{:ok, %{name: "john doe"}}

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!"]}}

iex> make(%{user: %{name: :string, age: {:integer, default: 21}}}, %{"user" => %{"name" => "john"}})
{:ok, %{user: %{name: "john", age: 21}}}

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}}