Last active
July 21, 2020 11:51
-
-
Save Ivor/0fe1ce561796297118bfddae35fd044d to your computer and use it in GitHub Desktop.
Quick and dirty way to get a struct to a map.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule DeepMap do | |
def deep_to_map(%DateTime{} = struct), do: DateTime.to_iso8601(struct) | |
def deep_to_map(%Date{} = struct), do: Date.to_iso8601(struct) | |
def deep_to_map(%NaiveDateTime{} = struct), do: NaiveDateTime.to_iso8601(struct) | |
def deep_to_map(%_{} = struct) do | |
struct | |
|> Map.from_struct() | |
|> deep_to_map() | |
end | |
def deep_to_map(map) when is_map(map) do | |
for {key, val} <- map, into: %{}, do: {key, deep_to_map(val)} | |
end | |
def deep_to_map(list) when is_list(list) do | |
Enum.map(list, &(deep_to_map(&1))) | |
end | |
def deep_to_map(not_a_map_or_a_struct) when is_binary(not_a_map_or_a_struct), | |
do: not_a_map_or_a_struct | |
def deep_to_map(not_a_map_or_a_struct) do | |
not_a_map_or_a_struct | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment