Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix derive with _ key #190

Merged
merged 1 commit into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions lib/encoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ end
defimpl Jason.Encoder, for: Any do
defmacro __deriving__(module, struct, opts) do
fields = fields_to_encode(struct, opts)
kv = Enum.map(fields, &{&1, generated_var(&1, __MODULE__)})
kv = Enum.map(fields, &{&1, generated_var(&1)})
escape = quote(do: escape)
encode_map = quote(do: encode_map)
encode_args = [escape, encode_map]
Expand All @@ -94,9 +94,12 @@ defimpl Jason.Encoder, for: Any do
end
end

# The same as Macro.var/2 except it sets generated: true
defp generated_var(name, context) do
{name, [generated: true], context}
# The same as Macro.var/2 except it sets generated: true and handles _ key
defp generated_var(:_) do
{:__, [generated: true], __MODULE__.Underscore}
end
defp generated_var(name) do
{name, [generated: true], __MODULE__}
end

def encode(%_{} = struct, _opts) do
Expand Down
8 changes: 8 additions & 0 deletions test/encode_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ defmodule Jason.EncoderTest do
defstruct name: "", size: 0
end

defmodule DerivedWeirdKey do
@derive Encoder
defstruct [:_]
end

defmodule NonDerived do
defstruct name: ""
end
Expand All @@ -154,6 +159,9 @@ defmodule Jason.EncoderTest do

derived_using_except = %DerivedUsingExcept{name: "derived using :except", size: 10}
assert to_json(derived_using_except) == ~s({"size":10})

derived_weird_key = %DerivedWeirdKey{}
assert to_json(derived_weird_key) == ~s({"_":null})
end

test "@derive validate `except:`" do
Expand Down
Loading