/
valuedate.rb
134 lines (109 loc) · 2.74 KB
/
valuedate.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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class Valuedate
class ValidationFailed < StandardError
attr_reader :errors
def initialize(errors)
super("validation failed with #{errors.size} errors")
@errors = errors
end
end
class Error
attr_reader :options
def initialize(options={})
@options = options
end
end
class Scope
def value
Value.new
end
def optional_value
OptionalValue.new
end
end
class Value < Valuedate
end
class OptionalValue < Valuedate
def call(value = nil)
value.nil? || super
end
end
attr_reader :errors
def initialize(&block)
@errors = []
@validators = []
if block
validator = Scope.new.instance_eval(&block)
@validators << validator if validator.respond_to?(:call)
end
end
def hash(schema={})
valid? do |value|
value ||= {}
schema.all? do |(key, validator)|
validator.call(value[key]) || collect_errors!(validator, key)
end
end
end
def call(value = nil)
@errors.clear
@validators.all? { |validator| validator.call(value) || collect_errors!(validator) }
end
alias :validate :call
def call!(value = nil)
call(value) or raise ValidationFailed.new(@errors)
end
alias :validate! :call!
def valid?(&block)
@validators << block
self
end
def collect_errors!(validator, key=nil)
case validator
when Valuedate
@errors.concat(validator.errors.map { |error| error.options[:key] ||= key; error })
end
false
end
def errors
@errors.uniq
end
def error(options={})
@errors << Error.new(options)
false
end
def method_missing(method, *args, &block)
if matcher = Valuedate.matchers[method]
valid? do |value|
matcher.call(value, *args, &block) || error(:matcher => method, :value => value, :args => args)
end
else
super
end
end
@matchers = {}
class << self
attr_reader :matchers
def validate(value, &block)
schema(&block).call(value)
end
def validate!(value, &block)
schema(&block).call!(value)
end
def schema(&block)
new(&block)
end
def matcher(name, &block)
undef_method(name) if respond_to?(name)
@matchers[name] = block
end
end
end
Valuedate.matcher(:equals) { |value, expected| value == expected }
Valuedate.matcher(:is_a) { |value, expected| value.is_a?(expected) }
Valuedate.matcher(:any) do |value, *validators|
validators.any? { |validator| validator.call(value) }
end
Valuedate.matcher(:in) { |value, expected| expected.include?(value) }
Valuedate.matcher(:is) { |*value, &block| block.call(*value) }
Valuedate.matcher(:not) { |*value, &block| !block.call(*value) }
Valuedate.matcher(:matches) { |value, expected| expected.match(value.to_s) }