File tree Expand file tree Collapse file tree 2 files changed +22
-0
lines changed Expand file tree Collapse file tree 2 files changed +22
-0
lines changed Original file line number Diff line number Diff line change @@ -38,5 +38,22 @@ defmodule Map do
38
38
end , map1 , map2
39
39
end
40
40
41
+ @ doc """
42
+ Converts a struct to map.
43
+
44
+ ## Example
45
+
46
+ defmodule User do
47
+ defstruct [:name]
48
+ end
49
+
50
+ Map.from_struct(%User{name: "valim"})
51
+ #=> %{name: "valim"}
52
+
53
+ """
54
+ def from_struct ( struct ) do
55
+ :maps . delete ( :__struct__ , struct )
56
+ end
57
+
41
58
def equal? ( % { } = map1 , % { } = map2 ) , do: map1 === map2
42
59
end
Original file line number Diff line number Diff line change @@ -124,6 +124,11 @@ defmodule MapTest do
124
124
end
125
125
end
126
126
127
+ test "map from struct" do
128
+ assert Map . from_struct ( % ExternalUser { name: "valim" } ) == % { name: "valim" , age: 27 }
129
+ assert Map . from_struct ( % { name: "valim" } ) == % { name: "valim" }
130
+ end
131
+
127
132
defmodule LocalUser do
128
133
defmodule NestedUser do
129
134
defstruct [ ]
You can’t perform that action at this time.
0 commit comments