From fc4c60b125d36902a869155522cf655e6c2f9b3a Mon Sep 17 00:00:00 2001 From: zimt28 <1764689+zimt28@users.noreply.github.com> Date: Fri, 7 Oct 2022 17:24:04 +0200 Subject: [PATCH] improvement: Allow a single `where` condition for validations (#407) --- lib/ash/resource/validation.ex | 23 +++++++++++++++++------ test/actions/validation_test.exs | 5 ++--- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/lib/ash/resource/validation.ex b/lib/ash/resource/validation.ex index b610faf1..a877aeaa 100644 --- a/lib/ash/resource/validation.ex +++ b/lib/ash/resource/validation.ex @@ -43,16 +43,17 @@ defmodule Ash.Resource.Validation do @callback init(Keyword.t()) :: {:ok, Keyword.t()} | {:error, String.t()} @callback validate(Ash.Changeset.t(), Keyword.t()) :: :ok | {:error, term} + @validation_type {:spark_behaviour, Ash.Resource.Validation, Ash.Resource.Validation.Builtins} + @schema [ validation: [ - type: {:spark_behaviour, Ash.Resource.Validation, Ash.Resource.Validation.Builtins}, + type: @validation_type, required: true, doc: "The module/opts pair of the validation", links: [] ], where: [ - type: - {:list, {:spark_behaviour, Ash.Resource.Validation, Ash.Resource.Validation.Builtins}}, + type: {:or, [@validation_type, {:list, @validation_type}]}, required: false, default: [], links: [ @@ -113,10 +114,20 @@ defmodule Ash.Resource.Validation do end @doc false - def transform(%{validation: {module, opts}} = validation) do + def transform(%{validation: {module, opts}, where: where} = validation) do case module.init(opts) do - {:ok, opts} -> {:ok, %{validation | validation: {module, opts}, module: module, opts: opts}} - {:error, error} -> {:error, error} + {:ok, opts} -> + {:ok, + %{ + validation + | validation: {module, opts}, + module: module, + opts: opts, + where: List.wrap(where) + }} + + {:error, error} -> + {:error, error} end end diff --git a/test/actions/validation_test.exs b/test/actions/validation_test.exs index cc4dbd40..cf6701e6 100644 --- a/test/actions/validation_test.exs +++ b/test/actions/validation_test.exs @@ -26,9 +26,8 @@ defmodule Ash.Test.Actions.ValidationTest do where([attribute_equals(:foo, true)]) end - validate attribute_does_not_equal(:status, "foo") do - where([attribute_equals(:foo, false)]) - end + validate attribute_does_not_equal(:status, "foo"), + where: attribute_equals(:foo, false) end attributes do