Skip to content

Add support for string-keyed attrs in from functions #7

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,12 @@ unless defaulted or provided as attributes to the constructor.
}
```

## String keyed attributes
The attributes map provided to the constructor functions can be either string-keyed or atom-key, not mixed.

Under the covers we are using [Ecto.Changeset.cast/4](https://hexdocs.pm/ecto/Ecto.Changeset.html#cast/4), to
copy and cast attributes into the struct being created.

## Installation
Because this plugin supports the interface defined by the `TypedStruct` macro, installation assumes you've already
added that dependency.
Expand Down
21 changes: 14 additions & 7 deletions lib/typed_struct_ctor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,20 @@ defmodule TypedStructCtor do

@doc false
def do_from(mod, base_struct, attrs) when is_struct(base_struct) do
attrs =
base_struct
|> Map.from_struct()
|> Map.drop(mod.__not_mapped__())
|> Map.merge(attrs)

TypedStructCtor.do_new(mod, attrs)
# `attrs` could be string-keyed map, use Ecto to convert to validated atom-keys
case cast(mod.__struct__(), attrs, mod.__all__(), force_changes: true) do
%{valid?: true, changes: valid_attrs} ->
merged_attrs =
base_struct
|> Map.from_struct()
|> Map.drop(mod.__not_mapped__())
|> Map.merge(valid_attrs)

TypedStructCtor.do_new(mod, merged_attrs)

other ->
other
end
end

def do_from(_mod, _base_struct, _attrs), do: {:error, :base_struct_must_be_a_struct}
Expand Down
6 changes: 3 additions & 3 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule TypedStructCtor.MixProject do
def project do
[
app: :typed_struct_ctor,
version: "0.1.1",
version: "0.1.2",
elixir: "~> 1.15",
start_permanent: Mix.env() == :prod,
deps: deps(),
Expand Down Expand Up @@ -35,14 +35,14 @@ defmodule TypedStructCtor.MixProject do
defp package() do
[
licenses: ["MIT"],
links: %{"Github" => "https://github.com/withbelay/typed_struct_ctor"}
links: %{"Github" => "https://github.com/leggebroten/typed_struct_ctor"}
]
end

defp deps do
[
{:credo, "~> 1.7", only: [:dev, :test]},
{:dialyxir, "~> 1.3", only: [:dev, :test]},
{:dialyxir, "~> 1.3", only: [:dev, :test], runtime: false},
{:ecto, "~> 3.10"},
{:ex_doc, "~> 0.30", only: :dev},
{:typedstruct, "~> 0.5.2"},
Expand Down
30 changes: 30 additions & 0 deletions test/typed_struct_ctor_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ defmodule Mappable do
plugin(TypedStructEctoChangeset)
plugin(TypedStructCtor)

field(:defaulted, :string, default: "defaulted")
field(:mapped_by_default, :string, default: "bar")
field(:id, :string, mappable?: false, default_apply: {Ecto.UUID, :generate, []})
end
Expand All @@ -75,6 +76,22 @@ defmodule TypedStructCtorTest do
})
end

test "when attributes are string keys, map to atoms" do
assert {:ok,
%AStruct{
not_required_defaulted: 1,
not_required_not_defaulted: 2,
required_defaulted: 3,
required_not_defaulted: 4
}} ==
AStruct.new(%{
"not_required_defaulted" => "1",
"not_required_not_defaulted" => "2",
"required_defaulted" => "3",
"required_not_defaulted" => "4"
})
end

test "when no attributes supplied, use defaults" do
assert {:error, message} = AStruct.new(%{})

Expand Down Expand Up @@ -192,6 +209,19 @@ defmodule TypedStructCtorTest do
assert mapped_struct.id == "baz"
end

test "when attributes have string keys, they're cast correctly as atom keys" do
original_struct = Mappable.new!(%{"mapped_by_default" => "foo"})

{:ok, %{id: "baz", mapped_by_default: "bar"}} =
Mappable.from(original_struct, %{"id" => "baz", "mapped_by_default" => "bar"})

{:ok, %{id: "baz", mapped_by_default: "foo"}} = Mappable.from(original_struct, %{"id" => "baz"})

{:ok, %{id: id, mapped_by_default: "foo"}} = Mappable.from(original_struct)
refute id == original_struct.id
{:ok, _uuid} = Ecto.UUID.cast(id)
end

test "when fails validation, return error tuple" do
original_struct = Mappable.new!(%{mapped_by_default: "foo"})
{:error, changeset} = Mappable.from(original_struct, %{mapped_by_default: nil})
Expand Down