Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add default build/2 and start encouraging struct!/2 instead of Map.merge/2 #30

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions lib/factoid.ex
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,43 @@ defmodule Factoid do
last_name: "Doe",
email_address: "jane-#{unique_integer()}@example.com",
}
|> Map.merge(attrs)
|> struct!(attrs)
end

def build(:user_avatar, attrs) do
%UserAvatar{
user: build(:user)
}
|> Map.merge(attrs)
|> struct!(attrs)
end
end
```

If you prefer, you can also just implement `build/1` and `Factoid` will
automatically generate the `build/2` function.

```elixir
def App.Factory do
@behaviour Factoid

use Factoid, repo: App.Repo

alias App.Schemas.User
alias App.Schemas.UserAvatar

@impl Factoid
def build(:user) do
%User{
first_name: "Jane",
last_name: "Doe",
email_address: "jane-#{unique_integer()}@example.com",
}
end

def build(:user_avatar) do
%UserAvatar{
user: build(:user)
}
end
end
```
Expand Down Expand Up @@ -118,6 +147,14 @@ defmodule Factoid do
@typedoc false
@type attrs :: map() | keyword()

@doc """
Builds a record with attributes.
"""
@spec build(factory_name(), attrs()) :: record()
def build(factory_name, attrs \\ %{}) do
factory_name |> then(&build(@repo, &1)) |> struct!(attrs)
end

@doc """
Inserts a record with attributes.
"""
Expand All @@ -135,6 +172,8 @@ defmodule Factoid do
Generates a UUID.
"""
def unique_uuid, do: Factoid.unique_uuid()

defoverridable build: 2
end
end

Expand Down