Class: RSchema::Schemas::FixedLengthArray

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

Overview

A schema that represents an array of fixed length

Each element in the fixed-length array has its own subschema

Examples:

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subschemas) ⇒ FixedLengthArray

Returns a new instance of FixedLengthArray.



18
19
20
# File 'lib/rschema/schemas/fixed_length_array.rb', line 18

def initialize(subschemas)
  @subschemas = subschemas
end

Instance Attribute Details

#subschemasObject (readonly)

Returns the value of attribute subschemas.



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

def subschemas
  @subschemas
end

Instance Method Details

#call(value, options) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rschema/schemas/fixed_length_array.rb', line 22

def call(value, options)
  unless value.kind_of?(Array)
    return Result.failure(Error.new(
      symbolic_name: :not_an_array,
      schema: self,
      value: value,
    ))
  end

  unless value.size == @subschemas.size
    return Result.failure(Error.new(
      symbolic_name: :incorrect_size,
      schema: self,
      value: value,
    ))
  end

  validate_value, error = apply_subschemas(value, options)
  if error.empty?
    Result.success(validate_value)
  else
    Result.failure(error)
  end
end

#with_wrapped_subschemas(wrapper) ⇒ Object



47
48
49
50
# File 'lib/rschema/schemas/fixed_length_array.rb', line 47

def with_wrapped_subschemas(wrapper)
  wrapped_subschemas = subschemas.map{ |ss| wrapper.wrap(ss) }
  self.class.new(wrapped_subschemas)
end