Skip to content

Commit 7baa361

Browse files
committed
simplify and correct deep_merge conflict handling and add test for it
1 parent b022659 commit 7baa361

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

lib/jsonapi/utils/include_tree.ex

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ defmodule JSONAPI.Utils.IncludeTree do
33
Internal utility for building trees of resource relationships
44
"""
55

6+
@spec deep_merge(Keyword.t(), Keyword.t()) :: Keyword.t()
67
def deep_merge(acc, []), do: acc
78

89
def deep_merge(acc, [{key, val} | tail]) do
@@ -11,8 +12,8 @@ defmodule JSONAPI.Utils.IncludeTree do
1112
key,
1213
val,
1314
fn
14-
[_first | _rest] = old_val -> deep_merge(old_val, val)
15-
old_val -> Keyword.put([], old_val, val)
15+
[_first | _rest] = old_val when is_list(val) -> deep_merge(old_val, val)
16+
_ -> val
1617
end
1718
)
1819
|> deep_merge(tail)

test/utils/include_tree_test.exs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,11 @@ defmodule JSONAPI.IncludeTreeTest do
66
items = [:test, :the, :path]
77
assert put_as_tree([], items, :boo) == [test: [the: [path: :boo]]]
88
end
9+
10+
test "deep_merge/2 handles string/keyword conflict by choosing second value" do
11+
# one direction
12+
assert [other: "thing", hi: [hello: "there"]] = deep_merge([other: "thing", hi: "there"], hi: [hello: "there"])
13+
# the other direction
14+
assert [hi: "there", other: "thing"] = deep_merge([hi: [hello: "there"]], other: "thing", hi: "there")
15+
end
916
end

0 commit comments

Comments
 (0)