Skip to content

Commit

Permalink
Fix derive with _ key
Browse files Browse the repository at this point in the history
Summary:

Test Plan:
  • Loading branch information
michalmuskala committed Jun 29, 2024
1 parent e5ccbcc commit 87c817c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
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

0 comments on commit 87c817c

Please sign in to comment.