@@ -7,7 +7,7 @@ module Validations
7
7
class CoerceValidator < Base
8
8
def validate_param! ( attr_name , params )
9
9
fail Grape ::Exceptions ::Validation , params : [ @scope . full_name ( attr_name ) ] , message_key : :coerce unless params . is_a? Hash
10
- new_value = coerce_value ( @option , params [ attr_name ] )
10
+ new_value = coerce_value ( params [ attr_name ] )
11
11
if valid_type? ( new_value )
12
12
params [ attr_name ] = new_value
13
13
else
@@ -50,27 +50,36 @@ def valid_type?(val)
50
50
end
51
51
end
52
52
53
- def coerce_value ( type , val )
53
+ def coerce_value ( val )
54
54
# Don't coerce things other than nil to Arrays or Hashes
55
55
return val || [ ] if type == Array
56
56
return val || Set . new if type == Set
57
57
return val || { } if type == Hash
58
58
59
- # To support custom types that Virtus can't easily coerce, pass in an
60
- # explicit coercer. Custom types must implement a `parse` class method.
61
- converter_options = { }
62
- if ParameterTypes . custom_type? ( type )
63
- converter_options [ :coercer ] = type . method ( :parse )
64
- end
65
-
66
- converter = Virtus ::Attribute . build ( type , converter_options )
67
59
converter . coerce ( val )
68
60
69
61
# not the prettiest but some invalid coercion can currently trigger
70
62
# errors in Virtus (see coerce_spec.rb:75)
71
63
rescue
72
64
InvalidValue . new
73
65
end
66
+
67
+ def type
68
+ @option
69
+ end
70
+
71
+ def converter
72
+ @converter ||=
73
+ begin
74
+ # To support custom types that Virtus can't easily coerce, pass in an
75
+ # explicit coercer. Custom types must implement a `parse` class method.
76
+ converter_options = { }
77
+ if ParameterTypes . custom_type? ( type )
78
+ converter_options [ :coercer ] = type . method ( :parse )
79
+ end
80
+ Virtus ::Attribute . build ( type , converter_options )
81
+ end
82
+ end
74
83
end
75
84
end
76
85
end
0 commit comments