Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load values into a Struct from a Map in Elixir [duplicate]

Tags:

elixir

Let's say I've a map with some user data:

iex(1)> user_map
#=> %{name: "Some User", email: "[email protected]", password: "*********"}

How can I load this into a %User{} struct (hopefully using some Rubyish Elixir Magic)?


I've currently tried these but all of them failed. Going through the Structs section on Elixir website.

user_struct = %{ %User{} | user_map }
user_struct = %{ %User{} | Enum.to_list(user_map) }
like image 795
Sheharyar Avatar asked Jun 23 '15 08:06

Sheharyar


1 Answers

Found the answer on the elixir-lang-talk mailing list. We can use the struct/2 method:

struct(User, user_map)
#=> %User{name: "Some User", email: "[email protected]", password: "*********"}

Another way, as mentioned by Dogbert, is to use Map.merge/2:

Map.merge(%User{}, user_map)
#=> %User{name: "Some User", email: "[email protected]", password: "*********"}

caveat from the comments: Map.merge cannot handle enforced keys on structs

like image 96
Sheharyar Avatar answered Oct 20 '22 16:10

Sheharyar