Croma.Struct

Utility module to define structs and some helper functions.

Using this module requires to prepare modules that represent each struct field. Each of per-field module must provide the following members:

Some helpers for defining such per-field modules are available.

To define a struct, use this module with a keyword list:

defmodule S do
  use Croma.Struct, field1_name: Field1Module, field2_name: Field2Module
end

Then the above code is converted to defstruct along with @type t.

This module also generates the following functions.

Examples

iex> defmodule F do
...>   @type t :: integer
...>   def validate(i) when is_integer(i), do: {:ok, i}
...>   def validate(_), do: {:error, :invalid_f}
...>   def default, do: 0
...> end

...> defmodule S do
...>   use Croma.Struct, f: F
...> end

...> S.validate([f: 5])
{:ok, %S{f: 5}}

...> S.validate(%{f: "not_an_integer"})
{:error, :invalid_f}

...> s = S.new([])
%S{f: 0}

...> S.update(s, [f: 2])
{:ok, %S{f: 2}}

...> S.update(s, %{"f" => "not_an_integer"})
{:error, :invalid_f}
Source