Cartograf v0.1.0 Cartograf View Source
Cartograf is a set of elixir macros for mapping fields from one struct to another. The goal is to make these struct-to-struct translations more robust and less cumbersome to write and maintian.
Basic Form
The basic form for using this module is of the form:
map Proj.A, Proj.B, :one_to_one do
[
let(:a, :aa),
let(:b, :bb),
let(:c, :cc),
let(:d, :dd)
]
end
This structure would create a function called one_to_one/1
within whatever module this the macro was invoked within.
The one_to_one/1
function would expect a struct of type Proj.A
and return a struct of type Proj.B
would be returned.
The struct returned would have the fields of the input struct, A
,
mapped to the fields of the returned struct, B
, thusly:
A | to | B |
---|---|---|
:a | → | :aa |
:b | → | :bb |
:c | → | :cc |
:d | → | :dd |
Design Philosophy
Beyond the basic use, there are a number of options that can
be used within a map
block beyond just the basic let(from, to)
form. However, it before introducing them, it is important to
understand the design philosophy and what this cartograf
is
meant to do.
cartograf
is supposed to be a tool, not a hazzard.
The point of this project is to create robust mappings from
one struct to another. As such, there are a few safeties in
place to protect the developer.
map()
does require that its input struct is of the correct type. The function generated leverages pattern matching on the argument to ensure that the struct type is the one declared when the map was specified.- All input fields must be handled. Each
map()
will ensure that each field of the input is mentioned in some capacity. If a field should not be included in in the output struct, no problem, just include adrop(input_key)
. The main purpose for this is catch instances where developers add fields to structs, but fail to update the maps.
Link to this section Summary
Functions
Allow for a field in the output to be set to a constant value
Allow for a field from the input to be excluded from the output
Specify where the a field in the input should be mapped to in the out
Creates a function in the the current module for mapping from struct to another
Used to specific a nested map within map()
Link to this section Functions
Allow for a field in the output to be set to a constant value.
Allow for a field from the input to be excluded from the output.
Specify where the a field in the input should be mapped to in the out.
Creates a function in the the current module for mapping from struct to another.
defmodule A, do: defstruct [:a, :b, :c]
defmodule B, do: defstruct [:aa, :bb, :cc]
defmodule YourModule do
use Cartograf
map A, B, :a_to_b do
[
let(:a, :aa),
let(:b, :bb),
let(:c, :cc)
]
end
end
iex> YourModule.a_to_b(%A{a: 1, b: "2", c: :d})
%B{aa: 1, bb: "2", cc: :d}
Used to specific a nested map within map()