Class: Grape::Validations::Types::ArrayCoercer

Inherits:
DryTypeCoercer show all
Defined in:
lib/grape/validations/types/array_coercer.rb

Overview

Coerces elements in an array. It might be an array of strings or integers or an array of arrays of integers.

It could've been possible to use an of method (https://dry-rb.org/gems/dry-types/main/array-with-member/) provided by dry-types. Unfortunately, it doesn't work for Grape because of behavior of Virtus which was used earlier, a Grape::Validations::Types::PrimitiveCoercer maintains Virtus behavior in coercing.

Direct Known Subclasses

SetCoercer

Instance Method Summary collapse

Methods inherited from DryTypeCoercer

coercer_instance_for, collection_coercer_for

Methods included from Util::FreezeOnNew

#new

Constructor Details

#initialize(type, strict: false) ⇒ ArrayCoercer

Returns a new instance of ArrayCoercer.



15
16
17
18
19
20
21
# File 'lib/grape/validations/types/array_coercer.rb', line 15

def initialize(type, strict: false)
  super
  @coercer = strict ? DryTypes::Strict::Array : DryTypes::Params::Array
  # Built eagerly: instances are shared across requests (and cached in
  # Types::CoercerCache), so no lazy state may be created at call time.
  @elem_coercer = DryTypeCoercer.coercer_instance_for(type.first, strict:)
end

Instance Method Details

#call(_val) ⇒ Object



23
24
25
26
27
28
# File 'lib/grape/validations/types/array_coercer.rb', line 23

def call(_val)
  collection = super
  return collection if collection.is_a?(InvalidValue)

  coerce_elements collection
end