Unpack (Unpack v0.1.7) View Source

Unpack has two functions. get lets you safely "unpack" any values from a nested map, struct or database object. from_struct will convert a struct (and nested structs) to a map.

Link to this section Summary

Functions

Deep convert a struct to a map, including nested struct values or nested lists.

Traverses nested data map or struct in order of keys list to return a value. Returns nil for missing keys, unloaded associations or empty maps.

Traverses nested data map or struct in order of keys list to return a value. Returns given default parameter for missing keys, unloaded associations or empty maps.

Link to this section Functions

Deep convert a struct to a map, including nested struct values or nested lists.

Examples

defmodule Game do
  defstruct [:name]
end

defmodule Developer do
  defstruct [:games]
end

struct = %Developer{games: [%Game{name: "RDR2"}]}

Unpack.from_struct(struct)
=> %{games: [%{name: "RDR2"}]}

Specs

get(map(), [any()]) :: any() | nil

Traverses nested data map or struct in order of keys list to return a value. Returns nil for missing keys, unloaded associations or empty maps.

Examples

iex> map = %{player: %{game: %{id: "game_id"}}}
iex> Unpack.get(map, [:player, :game, :id])
"game_id"

iex> struct = %{player: %Ecto.Association.NotLoaded{}}
iex> Unpack.get(struct, [:player, :game, :id])
nil
Link to this function

get(data, list, default)

View Source

Specs

get(map(), [any()], any()) :: any()

Traverses nested data map or struct in order of keys list to return a value. Returns given default parameter for missing keys, unloaded associations or empty maps.

Examples

iex> map = %{player: %{name: "George"}}
iex> Unpack.get(map, [:player, :email], "🙈")
"🙈"