Skip to content

Commit b965d8e

Browse files
author
José Valim
committed
Also allow structs atoms on Map.from_struct/1
1 parent 380bf1e commit b965d8e

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

lib/elixir/lib/map.ex

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,18 +41,28 @@ defmodule Map do
4141
@doc """
4242
Converts a struct to map.
4343
44+
It accepts the struct module or a struct itself and
45+
simply removes the `__struct__` field from the struct.
46+
4447
## Example
4548
4649
defmodule User do
4750
defstruct [:name]
4851
end
4952
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"}
5258
5359
"""
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)
5666
end
5767

5868
def equal?(%{} = map1, %{} = map2), do: map1 === map2

lib/elixir/test/elixir/map_test.exs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,9 @@ defmodule MapTest do
125125
end
126126

127127
test "map from struct" do
128+
assert Map.from_struct(ExternalUser) == %{name: "josé", age: 27}
128129
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
130131
end
131132

132133
defmodule LocalUser do

0 commit comments

Comments
 (0)