Skip to content

Commit

Permalink
Add struct support as the builder entries
Browse files Browse the repository at this point in the history
  • Loading branch information
shahryarjb committed Apr 30, 2024
1 parent b77ed4d commit a937051
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
6 changes: 6 additions & 0 deletions lib/macros/guarded_struct/derive/parser.ex
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ defmodule MishkaDeveloperTools.Macros.GuardedStruct.Derive.Parser do

def convert_to_atom_map({:ok, map}) when is_map(map), do: convert_to_atom_map(map)

def convert_to_atom_map(map) when is_struct(map) do
for {key, value} <- Map.from_struct(map),
into: %{},
do: {convert_key(key), convert_value(value)}
end

def convert_to_atom_map(map) when is_map(map) do
for {key, value} <- map, into: %{}, do: {convert_key(key), convert_value(value)}
end
Expand Down
14 changes: 11 additions & 3 deletions lib/macros/guarded_struct/guarded_struct.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1317,7 +1317,10 @@ defmodule GuardedStruct do
def builder(attrs, error \\ false)

def builder({key, attrs} = input, error)
when is_tuple(input) and is_map(attrs) and (is_list(key) or is_atom(key)) do
when is_tuple(input) and (is_map(attrs) or is_struct(attrs)) and
(is_list(key) or is_atom(key)) do
attrs = if(is_struct(attrs), do: Map.from_struct(attrs), else: attrs)

GuardedStruct.builder(
%{attrs: attrs, module: unquote(module), revaluation: unquote(escaped_list)},
key,
Expand All @@ -1327,7 +1330,10 @@ defmodule GuardedStruct do
end

def builder({key, attrs, type} = input, error)
when is_tuple(input) and is_map(attrs) and (is_list(key) or is_atom(key)) do
when is_tuple(input) and (is_map(attrs) or is_struct(attrs)) and
(is_list(key) or is_atom(key)) do
attrs = if(is_struct(attrs), do: Map.from_struct(attrs), else: attrs)

GuardedStruct.builder(
%{attrs: attrs, module: unquote(module), revaluation: unquote(escaped_list)},
key,
Expand All @@ -1336,7 +1342,9 @@ defmodule GuardedStruct do
)
end

def builder(attrs, error) when is_map(attrs) do
def builder(attrs, error) when is_map(attrs) or is_struct(attrs) do
attrs = if(is_struct(attrs), do: Map.from_struct(attrs), else: attrs)

GuardedStruct.builder(
%{attrs: attrs, module: unquote(module), revaluation: unquote(escaped_list)},
:root,
Expand Down

0 comments on commit a937051

Please sign in to comment.