Skip to content

Commit

Permalink
Do not delay execution nor bind over values in json_map, closes #94 (#95
Browse files Browse the repository at this point in the history
)
  • Loading branch information
josevalim authored and michalmuskala committed Oct 31, 2019
1 parent 97893dd commit 70b046a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/helpers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,20 @@ defmodule Jason.Helpers do
"""
defmacro json_map(kv) do
kv_values = Macro.expand(kv, __CALLER__)
kv_vars = Enum.map(kv_values, fn {key, _} -> {key, generated_var(key, Codegen)} end)

values = Enum.map(kv_values, &elem(&1, 1))
vars = Enum.map(kv_vars, &elem(&1, 1))

escape = quote(do: escape)
encode_map = quote(do: encode_map)
encode_args = [escape, encode_map]
kv_iodata = Codegen.build_kv_iodata(Macro.expand(kv, __CALLER__), encode_args)
kv_iodata = Codegen.build_kv_iodata(kv_vars, encode_args)

quote do
{unquote_splicing(vars)} = {unquote_splicing(values)}

%Fragment{
encode: fn {unquote(escape), unquote(encode_map)} ->
unquote(kv_iodata)
Expand Down
8 changes: 8 additions & 0 deletions test/helpers_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ defmodule Jason.HelpersTest do
doctest Helpers

describe "json_map/2" do
test "does not delay execution" do
%Fragment{} = json_map(
foo: Process.put(:json, :bar)
)

assert Process.get(:json) == :bar
end

test "produces same output as regular encoding" do
assert %Fragment{} = helper = json_map(bar: 2, baz: 3, foo: 1)
assert Jason.encode!(helper) == Jason.encode!(%{bar: 2, baz: 3, foo: 1})
Expand Down

0 comments on commit 70b046a

Please sign in to comment.