https://github.com/codedge-llc/chimera
Dead-simple conversion between Elixir structs
https://github.com/codedge-llc/chimera
elixir hex
Last synced: 12 months ago
JSON representation
Dead-simple conversion between Elixir structs
- Host: GitHub
- URL: https://github.com/codedge-llc/chimera
- Owner: codedge-llc
- License: mit
- Created: 2018-11-17T03:10:12.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2020-02-10T22:29:41.000Z (about 6 years ago)
- Last Synced: 2025-01-29T20:48:19.340Z (about 1 year ago)
- Topics: elixir, hex
- Language: Elixir
- Size: 11.7 KB
- Stars: 0
- Watchers: 4
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://travis-ci.org/codedge-llc/chimera)
[](https://hex.pm/packages/chimera)
[](https://hex.pm/packages/chimera)
# Chimera
Dead-simple conversion between Elixir structs
## Installation
Add chimera as a mix.exs dependency:
```elixir
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.
```elixir
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: "person@example.com"}
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.
```elixir
iex> user = %User{id: 1234, name: "Person", email: "person@example.com"}
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:
```elixir
iex> user = %User{id: 1234, name: "Person", email: "person@example.com"}
iex> Profile.new(user, map: [name: fn user -> String.upcase(user.email) end])
%Profile{id: 1234, name: "PERSON", avatar: nil}
```