- Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdesign_by_contract.rb
49 lines (40 loc) · 1015 Bytes
/
design_by_contract.rb
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
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),'..','lib'))
require'aspector'
# Design by contract example class
classExampleClass
definitialize
@transactions=[]
@total=0
end
defbuy(price)
@transactions << price
@total += price
end
defsell(price)
@transactions << price# Wrong
@total -= price
end
end
# Object extensions
classObject
defassert(bool,message='Assertion failure')
returnifbool
$stderr.putsmessage
$stderr.putscaller
end
end
# Aspect that we will apply
classContractExample < Aspector::Base
beforedo |price, &_block|
assertprice > 0,"Price is #{price}, should be greater than 0"
end
afterresult_arg: falsedo |*_, &_block|
sum=@transactions.reduce(&:+)
assert@total == sum,"Total(#{@total}) and sum of transactions(#{sum}) do not match"
end
end
ContractExample.applyExampleClass,methods: %w(buysell)
instance=ExampleClass.new
instance.buy(10)
instance.sell(10)
instance.sell(-10)