View Source Turnkey.Instructer (TurnkeyEx v0.0.1-alpha2)
Put maps into structs and return error tuple while enforcing keys.
struct/2
fails to enforce keys and struct!/2
crashes, so this module
wraps struct!/2
with try rescue.
It also handles assigning nested structs and critically plays nicely with @enforce_keys
Summary
Functions
Converts a map to a struct, enforcing the presence of all keys. If the conversion fails, returns an error tuple.
Functions
Converts a map to a struct, enforcing the presence of all keys. If the conversion fails, returns an error tuple.
Examples
iex> cat_params = %{
...> "user_name" => "test_user",
...> "friend" => %{"bark" => "abc123", "bite" => "data"}
...> }
iex> Turnkey.Instructer.instructify(
...> cat_params,
...> {Cat, friend: Cat.Dog}
...> )
{:ok, %Cat{friend: %Cat.Dog{bark: "abc123", bite: "data"}, user_name: "test_user"}}
iex> bad_dog = %{
...> "user_name" => "test_user",
...> "friend" => %{"bark" => "abc123"}
...> }
iex> Turnkey.Instructer.instructify(
...> bad_dog,
...> {Cat, friend: Cat.Dog}
...> )
{:error, {:instructer_parsing_error, "the following keys must also be given when building struct Turnkey.InstructerTest.Cat.Dog: [:bite] found only %{\"bark\" => \"abc123\"} as %{bark: \"abc123\"}"}}
iex> extra_keys_ignored = %{
...> "user_name" => "test_user",
...> "friend" => %{"bark" => "abc123", "bite" => "data", "fuggedabaoutit" => "abc123"}
...> }
iex> Turnkey.Instructer.instructify(
...> extra_keys_ignored,
...> {Cat, friend: Cat.Dog}
...> )
{:ok, %Cat{friend: %Cat.Dog{bark: "abc123", bite: "data"}, user_name: "test_user"}}