From 1262c8ffc2fb3b72be60742938ef2e3c01f64686 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nelson=20Estev=C3=A3o?= Date: Sat, 22 Jun 2024 12:38:03 +0100 Subject: [PATCH] feat: add default build/2 and start encouring struct!/2 instead of Map.merge/2 --- lib/factoid.ex | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/factoid.ex b/lib/factoid.ex index 6f7e122..ea1adf7 100644 --- a/lib/factoid.ex +++ b/lib/factoid.ex @@ -42,14 +42,14 @@ 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 ``` @@ -118,6 +118,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. """ @@ -135,6 +143,8 @@ defmodule Factoid do Generates a UUID. """ def unique_uuid, do: Factoid.unique_uuid() + + defoverridable build: 2 end end