Skip to content

Commit e326194

Browse files
authored
feat: struct schematics (#15)
1 parent c9a0eb6 commit e326194

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ There are 12 builtin schematics that you can use to build new schematics that fi
2828

2929
Literals can be used as schematics and are unified with `==` semantics.
3030

31+
Struct literals can be used as schematics, and the input is unified by seeing if it is an instance of the given struct.
32+
3133
## Example
3234

3335
Let's take a look at an example schematic for a JSON-RPC request for a bookstore API.

lib/schematic/unification.ex

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,17 @@ defimpl Schematic.Unification, for: Schematic do
1616
end
1717

1818
defimpl Schematic.Unification, for: Any do
19-
def unify(literal, value, _ \\ nil) do
19+
def unify(schematic, input, _ \\ nil)
20+
21+
def unify(%schematic_mod{}, %input_mod{} = input, _) do
22+
if schematic_mod == input_mod do
23+
{:ok, input}
24+
else
25+
{:error, "expected %#{schematic_mod}{}"}
26+
end
27+
end
28+
29+
def unify(literal, value, _) do
2030
if literal == value do
2131
{:ok, value}
2232
else

test/schematic_test.exs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,12 @@ defmodule SchematicTest do
348348
assert {:error, "expected false"} = unify(schematic, true)
349349
end
350350

351+
test "struct literal" do
352+
schematic = %HTTPRequest{}
353+
354+
assert {:ok, %HTTPRequest{body: "hi"}} = unify(schematic, %HTTPRequest{body: "hi"})
355+
end
356+
351357
test "raw/2" do
352358
schematic = raw(fn n, _ -> n > 10 end, message: "must be greater than 10")
353359

0 commit comments

Comments
 (0)