-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
defmodule Norm.Core.Delegate do | ||
@moduledoc false | ||
|
||
defstruct [:fun] | ||
|
||
def build(fun) when is_function(fun, 0) do | ||
%__MODULE__{fun: fun} | ||
end | ||
|
||
defimpl Norm.Conformer.Conformable do | ||
def conform(%{fun: fun}, input, path) do | ||
Norm.Conformer.Conformable.conform(fun.(), input, path) | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
defmodule Norm.Core.DelegateTest do | ||
use Norm.Case, async: true | ||
|
||
defmodule TreeTest do | ||
def spec() do | ||
schema(%{ | ||
"value" => spec(is_integer()), | ||
"left" => delegate(&TreeTest.spec/0), | ||
"right" => delegate(&TreeTest.spec/0) | ||
}) | ||
end | ||
end | ||
|
||
describe "delegate/1" do | ||
test "can write recursive specs with 'delegate'" do | ||
assert {:ok, _} = conform(%{}, TreeTest.spec()) | ||
|
||
assert {:ok, _} = | ||
conform( | ||
%{"value" => 4, "left" => %{"value" => 2}, "right" => %{"value" => 12}}, | ||
TreeTest.spec() | ||
) | ||
|
||
assert {:error, [%{input: "12", path: ["left", "left", "value"], spec: "is_integer()"}]} = | ||
conform( | ||
%{ | ||
"value" => 4, | ||
"left" => %{"value" => 2, "left" => %{"value" => "12"}}, | ||
"right" => %{"value" => 12} | ||
}, | ||
TreeTest.spec() | ||
) | ||
end | ||
end | ||
end |