Class: Grape::Validations::Types::MultipleTypeCoercer
- Inherits:
-
Object
- Object
- Grape::Validations::Types::MultipleTypeCoercer
- Extended by:
- Util::FreezeOnNew
- Defined in:
- lib/grape/validations/types/multiple_type_coercer.rb
Overview
This class is intended for use with Grape endpoint parameters that
have been declared to be of variant-type using the :types option.
MultipleTypeCoercer will build a coercer for each type declared
in the array passed to :types using build_coercer. It will
apply these coercers to parameter values in the order given to
:types, and will return the value returned by the first coercer
to successfully coerce the parameter value. Therefore if String is
an allowed type it should be declared last, since it will always
successfully "coerce" the value.
Instance Method Summary collapse
-
#call(val) ⇒ Object, InvalidValue
Coerces the given value.
-
#initialize(types, method = nil) ⇒ MultipleTypeCoercer
constructor
Construct a new coercer that will attempt to coerce values to the given list of types in the given order.
Methods included from Util::FreezeOnNew
Constructor Details
#initialize(types, method = nil) ⇒ MultipleTypeCoercer
Construct a new coercer that will attempt to coerce values to the given list of types in the given order.
24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/grape/validations/types/multiple_type_coercer.rb', line 24 def initialize(types, method = nil) @method = method.respond_to?(:parse) ? method.method(:parse) : method @type_coercers = types.map do |type| if Types.multiple? type VariantCollectionCoercer.new type, @method else Types.build_coercer type, strict: !@method.nil? end end.freeze end |
Instance Method Details
#call(val) ⇒ Object, InvalidValue
Coerces the given value.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/grape/validations/types/multiple_type_coercer.rb', line 42 def call(val) # once the value is coerced by the custom method, its type should be checked candidate = @method ? @method.call(val) : val coerced_val = InvalidValue.new @type_coercers.each do |coercer| coerced_val = coercer.call(candidate) return coerced_val unless coerced_val.is_a?(InvalidValue) end coerced_val end |