View Source Construct.Cast (Construct v3.0.3)

Module to make structure instance from provided params.

You can use it standalone, without defining structure, by providing types and params to make/3.

Summary

Functions

Function to compose structure instance from params

Types

options()

@type options() :: [{:error_values, boolean()}]

type()

@type type() :: {Construct.Type.t(), Keyword.t()}

types()

@type types() :: %{required(atom()) => type()}

Functions

make(struct_or_types, params, opts \\ [])

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