Skip to content

Latest commit

 

History

History
64 lines (48 loc) · 1.65 KB

README.md

File metadata and controls

64 lines (48 loc) · 1.65 KB

Build Status Hex.pm Hex.pm

Chimera

Dead-simple conversion between Elixir structs

Installation

Add chimera as a mix.exs dependency:

def deps do
  [
    {:chimera, "~> 0.3.0"}
  ]
end

Usage

Add use Chimera to your struct's module. It adds new/1 and new/2 functions that will create a new struct from any given map, struct or keyword list.

defmodule User do
  defstruct id: nil, name: nil, email: nil
  use Chimera
end

defmodule Profile do
  defstruct id: nil, name: "Person", avatar: nil
  use Chimera
end

iex> User.new(id: 1234, name: "Person")
%User{id: 1234, name: "Person", email: nil}

iex> user = %User{id: 1234, name: "Person", email: "[email protected]"}
iex> Profile.new(user)
%Profile{id: 1234, name: "Person", avatar: nil}

Custom Mappings

Use the optional :map argument to specify custom key mappings. :map is a keyword list whose keys correspond to the keys of the destination struct.

iex> user = %User{id: 1234, name: "Person", email: "[email protected]"}
iex> Profile.new(user, map: [name: nil])
%Profile{id: 1234, name: nil, avatar: nil}

Specify a function of arity 1 that takes the source struct as a parameter:

iex> user = %User{id: 1234, name: "Person", email: "[email protected]"}
iex> Profile.new(user, map: [name: fn user -> String.upcase(user.email) end])
%Profile{id: 1234, name: "PERSON", avatar: nil}