Class: RSchema::Schemas::VariableLengthArray

Inherits:
Object
  • Object
show all
Defined in:
lib/rschema/schemas/variable_length_array.rb

Overview

A schema that matches variable-length arrays, where all elements conform to a single subschema

Examples:

A variable-length array schema

schema = RSchema.define { array(_Integer) }
schema.valid?([1,2,3]) #=> true
schema.valid?([]) #=> true

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(element_schema) ⇒ VariableLengthArray

Returns a new instance of VariableLengthArray.



16
17
18
# File 'lib/rschema/schemas/variable_length_array.rb', line 16

def initialize(element_schema)
  @element_schema = element_schema
end

Instance Attribute Details

#element_schemaObject

Returns the value of attribute element_schema.



14
15
16
# File 'lib/rschema/schemas/variable_length_array.rb', line 14

def element_schema
  @element_schema
end

Instance Method Details

#call(value, options) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rschema/schemas/variable_length_array.rb', line 20

def call(value, options)
  if value.kind_of?(Array)
    validated_values, errors = validate_elements(value, options)
    if errors.empty?
      Result.success(validated_values)
    else
      Result.failure(errors)
    end
  else
    Result.failure(Error.new(
      schema: self,
      value: value,
      symbolic_name: :not_an_array,
    ))
  end
end

#validate_elements(array, options) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rschema/schemas/variable_length_array.rb', line 41

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

#with_wrapped_subschemas(wrapper) ⇒ Object



37
38
39
# File 'lib/rschema/schemas/variable_length_array.rb', line 37

def with_wrapped_subschemas(wrapper)
  self.class.new(wrapper.wrap(element_schema))
end