Skip to content

Instantly share code, notes, and snippets.

@wesleimp
Created September 27, 2023 20:33
Show Gist options
  • Save wesleimp/e54b66db55d021224b451933401d8508 to your computer and use it in GitHub Desktop.
Save wesleimp/e54b66db55d021224b451933401d8508 to your computer and use it in GitHub Desktop.
defmodule MapHelpers do
@iso8601_structs [
Date,
DateTime,
NaiveDateTime,
Time
]
@doc """
Transforms a struct and its inner fields to the given key type
"""
@spec from_struct(instance :: map()) :: map()
def from_struct(instance) do
instance
|> Map.drop([:__struct__, :__meta__])
|> Map.new(fn
{key, value} -> {key, do_cast_from_struct(value)}
end)
end
defp do_cast_from_struct(%schema{} = struct) do
case schema do
schema when schema in @iso8601_structs ->
struct
_ ->
struct
|> Map.from_struct()
|> do_cast_from_struct()
end
end
defp do_cast_from_struct(map) when is_map(map) do
map
|> Map.drop([:__meta__])
|> Map.to_list()
|> Enum.map(fn
{k, v} -> {k, do_cast_from_struct(v)}
end)
|> Enum.into(%{})
end
defp do_cast_from_struct(list) when is_list(list) do
Enum.map(list, fn
{k, v} -> {k, do_cast_from_struct(v)}
v -> do_cast_from_struct(v)
end)
end
defp do_cast_from_struct(value), do: value
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment