Skip to content

Instantly share code, notes, and snippets.

@opsb
Last active March 1, 2018 16:23
Show Gist options
  • Save opsb/2d776eb2852f86a24ea1ae0dc224bb20 to your computer and use it in GitHub Desktop.
Save opsb/2d776eb2852f86a24ea1ae0dc224bb20 to your computer and use it in GitHub Desktop.
Export elixir Ecto models as plain maps
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