Skip to content

Instantly share code, notes, and snippets.

@ialeke
Last active April 8, 2021 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ialeke/1995cabd5e7b2e4fe30537a03310113c to your computer and use it in GitHub Desktop.
Save ialeke/1995cabd5e7b2e4fe30537a03310113c to your computer and use it in GitHub Desktop.
Jason.Encoder ecto example, removing __meta__ and %Ecto.Association.NotLoaded{}
defimpl Jason.Encoder, for: [Example.Module1, Example.Module2] do
def encode(value, opts) do
value
|> process_for_json
|> Jason.Encode.map(opts)
end
def remove_unloaded({_field, %Ecto.Association.NotLoaded{}}, accum), do: accum
def remove_unloaded({key, %_{__meta__: _} = data_map}, accum) do
accum |> Keyword.put(key, process_for_json(data_map))
end
def remove_unloaded(field, accum), do: accum ++ [field]
def process_for_json(data) do
data
|> Map.from_struct()
|> Map.delete(:__meta__)
|> Enum.into([])
|> Enum.reduce([], &remove_unloaded/2)
|> Enum.into(%{})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment