diff --git a/lib/helpers.ex b/lib/helpers.ex index b40e92a..f94678d 100644 --- a/lib/helpers.ex +++ b/lib/helpers.ex @@ -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) diff --git a/test/helpers_test.exs b/test/helpers_test.exs index 31b57ec..80eb6f7 100644 --- a/test/helpers_test.exs +++ b/test/helpers_test.exs @@ -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})