Last active
March 1, 2018 16:23
-
-
Save opsb/2d776eb2852f86a24ea1ae0dc224bb20 to your computer and use it in GitHub Desktop.
Export elixir Ecto models as plain maps
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 Util.Ecto do | |
def export(model = %{__meta__: _meta, __struct__: _struct}) when is_map(model) do | |
stripped = | |
model | |
|> Map.from_struct() | |
|> Map.delete(:__meta__) | |
associations = model.__struct__.__schema__(:associations) | |
Enum.reduce(associations, stripped, fn assoc, model -> | |
Map.update!(model, assoc, &export/1) | |
end) | |
end | |
def export(%Ecto.Association.NotLoaded{}) do | |
nil | |
end | |
def export(items) when is_list(items) do | |
Enum.map(items, &export/1) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment