class RSchema::Schemas::VariableLengthArray
A schema that matches variable-length arrays, where all elements conform to a single subschema
@example A variable-length array schema
schema = RSchema.define { array(_Integer) } schema.valid?([1,2,3]) #=> true schema.valid?([]) #=> true
Attributes
element_schema[RW]
Public Class Methods
new(element_schema)
click to toggle source
# File lib/rschema/schemas/variable_length_array.rb, line 17 def initialize(element_schema) @element_schema = element_schema end
Public Instance Methods
call(value, options)
click to toggle source
# File lib/rschema/schemas/variable_length_array.rb, line 21 def call(value, options) return type_failure(value) unless value.is_a?(Array) validated_values, errors = validate_elements(value, options) if errors.empty? Result.success(validated_values) else Result.failure(errors) end end
with_wrapped_subschemas(wrapper)
click to toggle source
# File lib/rschema/schemas/variable_length_array.rb, line 32 def with_wrapped_subschemas(wrapper) self.class.new(wrapper.wrap(element_schema)) end
Private Instance Methods
type_failure(value)
click to toggle source
# File lib/rschema/schemas/variable_length_array.rb, line 38 def type_failure(value) Result.failure( Error.new( schema: self, value: value, symbolic_name: :not_an_array, ), ) end
validate_elements(array, options)
click to toggle source
# File lib/rschema/schemas/variable_length_array.rb, line 48 def validate_elements(array, options) errors = {} validated_values = [] array.each_with_index do |subvalue, idx| result = @element_schema.call(subvalue, options) if result.valid? validated_values[idx] = result.value else errors[idx] = result.error break if options.fail_fast? end end [validated_values, errors] end