File tree Expand file tree Collapse file tree 2 files changed +16
-5
lines changed Expand file tree Collapse file tree 2 files changed +16
-5
lines changed Original file line number Diff line number Diff line change @@ -41,18 +41,28 @@ defmodule Map do
41
41
@ doc """
42
42
Converts a struct to map.
43
43
44
+ It accepts the struct module or a struct itself and
45
+ simply removes the `__struct__` field from the struct.
46
+
44
47
## Example
45
48
46
49
defmodule User do
47
50
defstruct [:name]
48
51
end
49
52
50
- Map.from_struct(%User{name: "valim"})
51
- #=> %{name: "valim"}
53
+ Map.from_struct(User)
54
+ #=> %{name: nil}
55
+
56
+ Map.from_struct(%User{name: "john"})
57
+ #=> %{name: "john"}
52
58
53
59
"""
54
- def from_struct ( struct ) do
55
- :maps . delete ( :__struct__ , struct )
60
+ def from_struct ( struct ) when is_atom ( struct ) do
61
+ :maps . remove ( :__struct__ , struct . __struct__ )
62
+ end
63
+
64
+ def from_struct ( % { __struct__: _ } = struct ) do
65
+ :maps . remove ( :__struct__ , struct )
56
66
end
57
67
58
68
def equal? ( % { } = map1 , % { } = map2 ) , do: map1 === map2
Original file line number Diff line number Diff line change @@ -125,8 +125,9 @@ defmodule MapTest do
125
125
end
126
126
127
127
test "map from struct" do
128
+ assert Map . from_struct ( ExternalUser ) == % { name: "josé" , age: 27 }
128
129
assert Map . from_struct ( % ExternalUser { name: "valim" } ) == % { name: "valim" , age: 27 }
129
- assert Map . from_struct ( % { name: "valim" } ) == % { name: "valim" }
130
+ assert_raise FunctionClauseError , fn -> Map . from_struct ( % { name: "valim" } ) end
130
131
end
131
132
132
133
defmodule LocalUser do
You can’t perform that action at this time.
0 commit comments