Skip to content

Instantly share code, notes, and snippets.

@mrjbj
Forked from heyitsjames/encoder.ex
Created October 13, 2021 18:00
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 mrjbj/a7ca1a7481d928770a358f19fa2569b3 to your computer and use it in GitHub Desktop.
Save mrjbj/a7ca1a7481d928770a358f19fa2569b3 to your computer and use it in GitHub Desktop.
defmodule MyApp.Encoder do
@moduledoc """
General implementation for the Jason encoder to be used in Ecto schemas
"""
defmacro __using__(opts) do
drop_fields = Keyword.get(opts, :drop, [])
quote do
defimpl Jason.Encoder, for: [__MODULE__] do
defp cardinality_to_empty(:one), do: %{}
defp cardinality_to_empty(:many), do: []
def encode(struct, opts) do
struct
|> Map.from_struct()
|> Enum.reduce(%{}, fn
{k, %Ecto.Association.NotLoaded{} = v}, acc ->
Map.put(acc, k, cardinality_to_empty(v.__cardinality__))
{k, v}, acc ->
Map.put(acc, k, v)
end)
|> Map.drop([:__meta__, :__struct__] ++ unquote(drop_fields))
|> Jason.Encode.map(opts)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment