Skip to content

Commit

Permalink
fix: don't double wrap casted struct instances in {:ok, {:ok, ...}}
Browse files Browse the repository at this point in the history
fix: support mixed key types in input maps for structs
  • Loading branch information
zachdaniel committed Nov 5, 2024
1 parent 0807317 commit 163dbe8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
21 changes: 10 additions & 11 deletions lib/ash/type/struct.ex
Original file line number Diff line number Diff line change
Expand Up @@ -273,17 +273,16 @@ defmodule Ash.Type.Struct do
if Enum.all?(keys, &is_atom/1) do
{:ok, struct(struct, value)}
else
{:ok,
Map.delete(struct.__struct__, :__struct__)
|> Enum.reduce({:ok, struct(struct)}, fn {key, _value}, {:ok, acc} ->
case Map.fetch(value, to_string(key)) do
{:ok, val} ->
{:ok, Map.put(acc, key, val)}

:error ->
{:ok, acc}
end
end)}
Map.delete(struct.__struct__(), :__struct__)
|> Enum.reduce({:ok, struct(struct)}, fn {key, _value}, {:ok, acc} ->
with :error <- Map.fetch(value, key),
:error <- Map.fetch(value, to_string(key)) do
{:ok, acc}
else
{:ok, val} ->
{:ok, Map.put(acc, key, val)}
end
end)
end
end
end
Expand Down
16 changes: 16 additions & 0 deletions test/type/struct_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ defmodule Type.StructTest do
defstruct [:foo, :bar]
end

defmodule Embedded do
use Ash.Resource, data_layer: :embedded

attributes do
attribute :name, :string, allow_nil?: false
attribute :title, :string, allow_nil?: false
end
end

defmodule Post do
@moduledoc false
use Ash.Resource, domain: Domain, data_layer: Ash.DataLayer.Ets
Expand Down Expand Up @@ -42,6 +51,13 @@ defmodule Type.StructTest do
end
end

test "an embedded resource can be used" do
assert {:ok, %Embedded{name: "fred", title: "title"}} =
Ash.Type.apply_constraints(Ash.Type.Struct, %{"name" => "fred", :title => "title"},
instance_of: Embedded
)
end

test "it handles valid maps" do
changeset =
Post
Expand Down

0 comments on commit 163dbe8

Please sign in to comment.