Class: Grape::Validations::Types::VariantCollectionCoercer
- Inherits:
-
Object
- Object
- Grape::Validations::Types::VariantCollectionCoercer
- Defined in:
- lib/grape/validations/types/variant_collection_coercer.rb
Overview
This class wraps MultipleTypeCoercer, for use with collections that allow members of more than one type.
Instance Method Summary collapse
-
#call(value) ⇒ Array<Object>, ...
Coerce the given value.
-
#initialize(types, method = nil) ⇒ VariantCollectionCoercer
constructor
Construct a new coercer that will attempt to coerce a list of values such that all members are of one of the given types.
-
#to_s ⇒ Object
Returns the Grape DSL notation for this coercer, e.g.
Constructor Details
#initialize(types, method = nil) ⇒ VariantCollectionCoercer
Construct a new coercer that will attempt to coerce a list of values such that all members are of one of the given types. The container may also optionally be coerced to a Set. An arbitrary coercion method may be supplied, which will be passed the entire collection as a parameter and should return a new collection, or may return the same one if no coercion was required.
20 21 22 23 24 25 26 27 |
# File 'lib/grape/validations/types/variant_collection_coercer.rb', line 20 def initialize(types, method = nil) @types = types @method = method.respond_to?(:parse) ? method.method(:parse) : method # If we have a coercion method, pass it in here to save # building another one, even though we call it directly. @member_coercer = MultipleTypeCoercer.new types, method end |
Instance Method Details
#call(value) ⇒ Array<Object>, ...
Coerce the given value.
43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/grape/validations/types/variant_collection_coercer.rb', line 43 def call(value) return unless value.is_a? Array value = if @method @method.call(value) else value.map { |v| @member_coercer.call(v) } end return Set.new value if @types.is_a? Set value end |
#to_s ⇒ Object
Returns the Grape DSL notation for this coercer, e.g. “Array[Integer, String]”. Distinct from the plain-array string “[Integer, String]” produced by the types: keyword, which lets documentation tools tell the two apart.
32 33 34 35 |
# File 'lib/grape/validations/types/variant_collection_coercer.rb', line 32 def to_s container = @types.is_a?(Set) ? 'Set' : 'Array' "#{container}[#{@types.join(', ')}]" end |