Skip to content

Commit b1d8e4e

Browse files
committed
support for structs
1 parent 7a1d25a commit b1d8e4e

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

lib/atomic_map.ex

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
defmodule AtomicMap do
22
def convert(v, opts \\ [])
3+
4+
def convert(struct=%{__struct__: type}, opts) do
5+
struct
6+
|> Map.from_struct
7+
|> convert(opts)
8+
|> Map.put(:__struct__, type)
9+
end
10+
311
def convert(map, opts) when is_map(map) do
412
safe = Keyword.get(opts, :safe, true)
513
map |> Enum.reduce(%{}, fn({k,v}, acc)->

test/atomic_map_test.exs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ defmodule AtomicMapTest do
22
use ExUnit.Case
33
doctest AtomicMap
44

5+
defmodule MyStruct do
6+
defstruct first: nil, second: nil
7+
end
8+
59
test "works with maps" do
610
input = %{"a" => 2, "b" => %{"c" => 4}}
711
expected = %{a: 2, b: %{c: 4}}
@@ -38,6 +42,18 @@ defmodule AtomicMapTest do
3842
assert AtomicMap.convert(input) == expected
3943
end
4044

45+
test "works with structs" do
46+
input = %AtomicMapTest.MyStruct{first: [%{"a" => 1}]}
47+
expected = %AtomicMapTest.MyStruct{first: [%{a: 1}]}
48+
assert AtomicMap.convert(input) == expected
49+
end
50+
51+
test "works with nested structs" do
52+
input = %AtomicMapTest.MyStruct{first: [%AtomicMapTest.MyStruct{first: %{"b" => 1}}]}
53+
expected = %AtomicMapTest.MyStruct{first: [%AtomicMapTest.MyStruct{first: %{b: 1}}]}
54+
assert AtomicMap.convert(input) == expected
55+
end
56+
4157
test "raises for not existing atoms" do
4258
assert_raise ArgumentError, fn ->
4359
input = %{"a" => 2, "b" => %{"c" => 4}, "__not___existing__" => 5}

0 commit comments

Comments
 (0)