class RSchema::Schemas::FixedLengthArray
A schema that represents an array of fixed length
Each element in the fixed-length array has its own subschema
@example A fixed-length array schema
schema = RSchema.define { array(_Integer, _String) } schema.valid?([5, "hello"]) #=> true schema.valid?([5]) #=> false schema.valid?([5, "hello", "world"]) #=> false
Attributes
subschemas[R]
Public Class Methods
new(subschemas)
click to toggle source
# File lib/rschema/schemas/fixed_length_array.rb, line 19 def initialize(subschemas) @subschemas = subschemas end
Public Instance Methods
call(value, options)
click to toggle source
# File lib/rschema/schemas/fixed_length_array.rb, line 23 def call(value, options) return type_failure(value) unless value.is_a?(Array) return size_failure(value) unless value.size == @subschemas.size validated_array, error = apply_subschemas(value, options) if error.empty? Result.success(validated_array) else Result.failure(error) end end
with_wrapped_subschemas(wrapper)
click to toggle source
# File lib/rschema/schemas/fixed_length_array.rb, line 35 def with_wrapped_subschemas(wrapper) wrapped_subschemas = subschemas.map { |ss| wrapper.wrap(ss) } self.class.new(wrapped_subschemas) end
Private Instance Methods
apply_subschemas(array, options)
click to toggle source
# File lib/rschema/schemas/fixed_length_array.rb, line 42 def apply_subschemas(array, options) validated_array = [] errors = {} array.zip(@subschemas).each_with_index do |(subvalue, subschema), idx| result = subschema.call(subvalue, options) if result.valid? validated_array << result.value else errors[idx] = result.error break if options.fail_fast? end end [validated_array, errors] end
size_failure(value)
click to toggle source
# File lib/rschema/schemas/fixed_length_array.rb, line 69 def size_failure(value) Result.failure( Error.new( symbolic_name: :incorrect_size, schema: self, value: value, ), ) end
type_failure(value)
click to toggle source
# File lib/rschema/schemas/fixed_length_array.rb, line 59 def type_failure(value) Result.failure( Error.new( symbolic_name: :not_an_array, schema: self, value: value, ), ) end