Skip to content

Commit

Permalink
Support struct default values
Browse files Browse the repository at this point in the history
The required fields must appear first in the defstruct, followed by
2-tuples with the default value protected by `Macro.escape/1`
  • Loading branch information
lifelenz authored and edgurgel committed Sep 11, 2024
1 parent cabca76 commit 7a039df
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
20 changes: 18 additions & 2 deletions lib/mimic/module.ex
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,27 @@ defmodule Mimic.Module do

defp generate_mimic_struct(module) do
if function_exported?(module, :__info__, 1) && module.__info__(:struct) != nil do
required_fields = for %{field: field, required: true} <- module.__info__(:struct), do: field
struct_info =
module.__info__(:struct)
|> Enum.split_with(& &1.required)
|> Tuple.to_list()
|> List.flatten()

required_fields = for %{field: field, required: true} <- struct_info, do: field
struct_template = Map.from_struct(module.__struct__())

struct_params =
for %{field: field, required: required} <- struct_info do
if required do
field
else
{field, Macro.escape(struct_template[field])}
end
end

quote do
@enforce_keys unquote(required_fields)
defstruct unquote(for %{field: field} <- module.__info__(:struct), do: field)
defstruct unquote(struct_params)
end
end
end
Expand Down
15 changes: 14 additions & 1 deletion test/mimic_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -994,10 +994,23 @@ defmodule Mimic.Test do
assert Structs.__info__(:struct) == [
%{field: :foo, required: true},
%{field: :bar, required: true},
%{field: :default, required: false}
%{field: :default, required: false},
%{field: :map_default, required: false}
]
end

test "copies struct fields with default values" do
Structs
|> stub(:foo, fn -> :stubbed end)

assert Structs.__struct__() == %Structs{
foo: nil,
bar: nil,
default: "123",
map_default: %{}
}
end

test "copies struct fields" do
StructNoEnforceKeys
|> stub(:bar, fn -> :stubbed end)
Expand Down
2 changes: 1 addition & 1 deletion test/support/test_modules.ex
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ end
defmodule Structs do
@moduledoc false
@enforce_keys [:foo, :bar]
defstruct [:foo, :bar, default: "123"]
defstruct [:foo, :bar, default: "123", map_default: %{}]
def foo, do: nil
end

Expand Down

0 comments on commit 7a039df

Please sign in to comment.