Skip to content

Commit f6e4091

Browse files
committed
More work on param validation
1 parent 244be97 commit f6e4091

2 files changed

Lines changed: 29 additions & 12 deletions

File tree

lib/syntropy/context.rb

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,30 +17,42 @@ def params
1717
def validate_param(name, *clauses)
1818
value = @request.query[name]
1919
clauses.each do |c|
20-
valid = is_valid_param?(value, c)
20+
valid = param_is_valid?(value, c)
2121
raise(Syntropy::ValidationError, 'Validation error') if !valid
22-
if c == Integer
23-
value = value.to_i
24-
elsif c == Float
25-
value = value.to_f
26-
end
22+
value = param_convert(value, c)
2723
end
2824
value
2925
end
3026

27+
BOOL_REGEXP = /^(t|f|true|false|on|off|1|0|yes|no)$/
28+
BOOL_TRUE_REGEXP = /^(t|true|on|1|yes)$/
3129
INTEGER_REGEXP = /^[\+\-]?[0-9]+$/
3230
FLOAT_REGEXP = /^[\+\-]?[0-9]+(\.[0-9]+)?$/
3331

34-
def is_valid_param?(value, cond)
35-
if cond == Integer
36-
return (value.is_a?(String) && value =~ INTEGER_REGEXP)
32+
def param_is_valid?(value, cond)
33+
if cond == :bool
34+
return (value && value =~ BOOL_REGEXP)
35+
elsif cond == Integer
36+
return (value && value =~ INTEGER_REGEXP)
3737
elsif cond == Float
38-
return (value.is_a?(String) && value =~ FLOAT_REGEXP)
38+
return (value && value =~ FLOAT_REGEXP)
3939
elsif cond.is_a?(Array)
40-
return cond.any? { |c| is_valid_param?(value, c) }
40+
return cond.any? { |c| param_is_valid?(value, c) }
4141
end
4242

4343
cond === value
4444
end
45+
46+
def param_convert(value, klass)
47+
if klass == :bool
48+
value = value =~ BOOL_TRUE_REGEXP ? true : false
49+
elsif klass == Integer
50+
value = value.to_i
51+
elsif klass == Float
52+
value = value.to_f
53+
else
54+
value
55+
end
56+
end
4557
end
4658
end

test/test_context.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
class ContextTest < Minitest::Test
66
def setup
7-
@req = mock_req(':method' => 'GET', ':path' => '/foo?q=foo&x=bar&y=123')
7+
@req = mock_req(':method' => 'GET', ':path' => '/foo?q=foo&x=bar&y=123&z1=t&z2=f')
88
@ctx = Syntropy::Context.new(@req)
99
end
1010

@@ -25,11 +25,16 @@ def test_validate_param
2525
assert_equal 123, @ctx.validate_param(:y, Integer, 120..125)
2626
assert_equal 123.0, @ctx.validate_param(:y, Float)
2727

28+
assert_equal true, @ctx.validate_param(:z1, :bool)
29+
assert_equal false, @ctx.validate_param(:z2, :bool)
30+
2831
assert_raises(VE) { @ctx.validate_param(:azerty, String) }
2932
assert_raises(VE) { @ctx.validate_param(:q, Integer) }
3033
assert_raises(VE) { @ctx.validate_param(:q, Float) }
3134
assert_raises(VE) { @ctx.validate_param(:q, nil) }
3235

3336
assert_raises(VE) { @ctx.validate_param(:y, Integer, 1..100) }
37+
38+
assert_raises(VE) { @ctx.validate_param(:y, :bool) }
3439
end
3540
end

0 commit comments

Comments
 (0)