-
Notifications
You must be signed in to change notification settings - Fork 3
/
oath.ex
88 lines (72 loc) · 1.92 KB
/
oath.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
defmodule Oath do
@moduledoc """
Oath provides a system for utilizing design by contract in elixir.
## Pre and Post conditions
You can decorate any of your functions with preconditions and postconditions.
```elixir
@decorator pre("inputs are ints", & is_integer(&1) && is_integer(&2))
@decorate post("the result must be greater than a or b", fn a, b, result ->
result >= a && result >= b
end)
def add(a, b) do
a + b
end
```
If your callers provide incorrect data or your function returns incorrect repsonses, an exception will be thrown.
"""
use Decorator.Define, [pre: 2, post: 2]
@doc false
def pre(text, condition, body, context) do
arg_names = Enum.map(context.args, fn {name, _, _} -> name end)
fn_name = fn_name(context)
if enabled?() do
quote do
contract = Oath.Contract.new(
:pre,
unquote(text),
unquote(condition),
unquote(context.args),
unquote(arg_names),
unquote(fn_name)
)
Oath.Contract.validate(contract)
unquote(body)
end
else
quote do
unquote(body)
end
end
end
@doc false
def post(text, condition, body, context) do
arg_names = Enum.map(context.args, fn {name, _, _} -> name end) ++ [:result]
fn_name = fn_name(context)
if enabled?() do
quote do
result = unquote(body)
contract = Oath.Contract.new(
:post,
unquote(text),
unquote(condition),
unquote(context.args) ++ [result],
unquote(arg_names),
unquote(fn_name)
)
Oath.Contract.validate(contract)
result
end
else
quote do
unquote(body)
end
end
end
@doc false
def fn_name(context) do
"#{context.module}.#{context.name}/#{context.arity}"
end
defp enabled? do
Application.get_env(:oath, :enable_contracts, false)
end
end