lib/grape/validations/validators/coerce.rb in grape-0.14.0 vs lib/grape/validations/validators/coerce.rb in grape-0.15.0
- old
+ new
@@ -3,22 +3,35 @@
Boolean = Virtus::Attribute::Boolean
end
module Validations
class CoerceValidator < Base
+ def initialize(*_args)
+ super
+ @converter = Types.build_coercer(type, @option[:method])
+ end
+
def validate_param!(attr_name, params)
- fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message_key: :coerce unless params.is_a? Hash
+ fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: message(:coerce) unless params.is_a? Hash
new_value = coerce_value(params[attr_name])
if valid_type?(new_value)
params[attr_name] = new_value
else
- fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message_key: :coerce
+ fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: message(:coerce)
end
end
private
+ # @!attribute [r] converter
+ # Object that will be used for parameter coercion and type checking.
+ #
+ # See {Types.build_coercer}
+ #
+ # @return [Virtus::Attribute]
+ attr_reader :converter
+
def valid_type?(val)
# Special value to denote coercion failure
return false if val.instance_of?(Types::InvalidValue)
# Allow nil, to ignore when a parameter is absent
@@ -45,21 +58,10 @@
# Type to which the parameter will be coerced.
#
# @return [Class]
def type
- @option[:type]
- end
-
- # Create and cache the attribute object
- # that will be used for parameter coercion
- # and type checking.
- #
- # See {Types.build_coercer}
- #
- # @return [Virtus::Attribute]
- def converter
- @converter ||= Types.build_coercer(type, @option[:method])
+ @option[:type].is_a?(Hash) ? @option[:type][:value] : @option[:type]
end
end
end
end