Transformable v0.1.0 Transformable protocol
Transform arbitrary maps and keyword lists into structs.
This is really a wrapper around struct/2
, with some additional preprocessing
logic to handle things like default values and data structures with either
string or atom keys.
Transformable is defined as a Protocol with an Any implementation. You can
write your own implementation and use transform/2
to specify custom outputs.
Link to this section Summary
Functions
Takes a map or keyword list and a target, and transforms the former into the latter
Link to this section Types
Link to this type
t()
t()
t() :: term()
t() :: term()
Link to this section Functions
Link to this function
transform(entity, opts)
Takes a map or keyword list and a target, and transforms the former into the latter.
The target can be either a struct, a module that exposes a struct, or a keyword list with options. Valid options are:
as
- The transform target (struct or module)default
- Overrides the default value defined in the target struct with the value provided
Examples
# Our target
defmodule Tester do
defstruct [:id, name: ""]
end
# The target is just a module alias
iex> Transformable.transform(%{id: 1}, Tester)
%Tester{id: 1, name: ""}
# The target is a struct
iex> Transformable.transform(%{id: 1}, %Tester{})
%Tester{id: 1, name: ""}
# With options
iex> Transformable.transform(%{id: 1}, as: Tester, default: false)
%Tester{id: 1, name: false}
# The data to transform can also have string keys
iex> Transformable.transform(%{"id" => 1}, Tester)
%Tester{id: 1, name: ""}
# OR the data to transform can be a keyword list
iex> Transformable.transform([id: 1], Tester)
%Tester{id: 1, name: ""}