Skip to content

Commit

Permalink
Add match?
Browse files Browse the repository at this point in the history
  • Loading branch information
solnic committed Sep 20, 2023
1 parent f9e2846 commit e69ed08
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/drops/predicates.ex
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ defmodule Drops.Predicates do
def size?(size, value) when is_list(value) and length(value) != size,
do: {:error, {:size?, [size, value]}}

def match?(regexp, value) do
if String.match?(value, regexp),
do: {:ok, value},
else: {:error, {:match?, [regexp, value]}}
end

def max_size?(size, value) when is_map(value) and map_size(value) <= size,
do: {:ok, value}

Expand Down
17 changes: 17 additions & 0 deletions test/contract/predicates_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -472,4 +472,21 @@ defmodule Drops.PredicatesTest do
contract.conform(%{test: [1, 2]})
end
end

describe "match?/2" do
contract do
schema do
%{required(:test) => type(:string, match?: ~r/\d+/)}
end
end

test "returns success when the value matches the regexp", %{contract: contract} do
assert {:ok, %{test: "312"}} = contract.conform(%{test: "312"})
end

test "returns success when the value doesn't match the regexp", %{contract: contract} do
assert {:error, [{:error, {:match?, [:test], [~r/\d+/, "Hello"]}}]} =
contract.conform(%{test: "Hello"})
end
end
end

0 comments on commit e69ed08

Please sign in to comment.