-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrule_base.rb
58 lines (49 loc) · 1.17 KB
/
rule_base.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
50
51
52
53
54
55
56
57
58
class RuleBase
attr_reader :error_message,
:successor,
:if_valid_then_execute, #The action to perform once when this rule passes validation.
:if_invalid_then_execute #The action to perform once when this rule fails validation.
def validate
@valid = true
on_validate
if valid?
if successor
successor.validate
invalidate(successor.error_message) if !successor.valid?
end
if @if_valid_then_execute
@if_valid_then_execute.call(self)
@if_valid_then_execute = nil
end
else
if @if_invalid_then_execute
@if_invalid_then_execute.call(self)
@if_invalid_then_execute = nil
end
end
return self
end
def valid?
@valid
end
def if_valid_then_validate(rule)
@successor = rule
self
end
def if_valid_then_execute(method)
@if_valid_then_execute = method
self
end
def if_invalid_then_execute(method)
@if_invalid_then_execute = method
self
end
protected
def on_validate
raise "on_validate must be implemented"
end
def invalidate(message)
@error_message = message
@valid = false
end
end