Module: HashParams::Validator
- Included in:
- HashParams
- Defined in:
- lib/hash_params/validator.rb
Defined Under Namespace
Classes: CoercionError, ValidationError
Instance Method Summary
collapse
Instance Method Details
#validate(param, type = nil, validations = {}) ⇒ Object
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
|
# File 'lib/hash_params/validator.rb', line 14
def validate(param, type=nil, validations={})
coercions = Array(validations[:coerce]) << type
if param.nil? && validations[:default]
param = validations[:default].respond_to?(:call) ? validations[:default].call() : validations[:default]
end
if validations[:validate] && validations[:validate].respond_to?(:call)
param = validations.delete(:validate).call(param)
end
if block_given? && !param.is_a?(Hash)
param = yield(param, validations)
end
coercions.each do |c|
param = coerce(param, c, validations)
end
if param.is_a?(Hash)
param = if block_given?
HashParams::HashValidator.new.validate_hash(param, validations, &Proc.new)
else
HashParams::HashValidator.new.validate_hash(param, validations)
end
end
if validations[:required] && param.nil?
raise ValidationError.new('Required Parameter missing and has no default specified')
end
error = nil
validations.each do |key, value|
error = case key
when :blank
'Parameter cannot be blank' if !value && (param.nil? || (param.respond_to?(:empty) && param.empty)) when :format
"#{param} must be a string if using the format validation" && next unless param.kind_of?(String)
"#{param} must match format #{value}" unless param =~ value
when :is
"#{param} must be #{value}" unless param === value
when :in, :within, :range
"#{param} must be within #{value}" unless value.respond_to?(:include) ? value.include?(param) : Array(value).include?(param)
when :min
"#{param} cannot be less than #{value}" unless value <= param
when :max
"#{param} cannot be greater than #{value}" unless value >= param
when :min_length
"#{param} cannot have length less than #{value}" unless value <= param.length
when :max_length
"#{param} cannot have length greater than #{value}" unless value >= param.length
else
nil
end
end
raise ValidationError.new(error) if error
param
end
|
#with_binding(&code) ⇒ Object