Class: T::Types::FixedArray

Inherits:
Base
  • Object
show all
Defined in:
lib/types/types/fixed_array.rb

Overview

Takes a list of types. Validates each item in an array using the type in the same position in the list.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#==, #error_message_for_obj, #error_message_for_obj_recursive, #hash, method_added, #subtype_of?, #to_s, #validate!

Constructor Details

#initialize(types) ⇒ FixedArray

Returns a new instance of FixedArray.



11
12
13
# File 'lib/types/types/fixed_array.rb', line 11

def initialize(types)
  @types = types.map {|type| T::Utils.coerce(type)}
end

Instance Attribute Details

#typesObject (readonly)

Returns the value of attribute types.



9
10
11
# File 'lib/types/types/fixed_array.rb', line 9

def types
  @types
end

Instance Method Details

#describe_obj(obj) ⇒ Object

This gives us better errors, e.g.: “Expected [String, Symbol], got [String, String]” instead of “Expected [String, Symbol], got Array”.

overrides Base



86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/types/types/fixed_array.rb', line 86

def describe_obj(obj)
  if obj.is_a?(Array)
    if obj.length == @types.length
      item_classes = obj.map(&:class).join(', ')
      "type [#{item_classes}]"
    else
      "array of size #{obj.length}"
    end
  else
    super
  end
end

#nameObject

overrides Base



16
17
18
# File 'lib/types/types/fixed_array.rb', line 16

def name
  "[#{@types.join(', ')}]"
end

#recursively_valid?(obj) ⇒ Boolean

overrides Base

Returns:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/types/types/fixed_array.rb', line 21

def recursively_valid?(obj)
  if obj.is_a?(Array) && obj.length == @types.length
    i = 0
    while i < @types.length
      if !@types[i].recursively_valid?(obj[i])
        return false
      end
      i += 1
    end
    true
  else
    false
  end
end

#valid?(obj) ⇒ Boolean

overrides Base

Returns:



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/types/types/fixed_array.rb', line 37

def valid?(obj)
  if obj.is_a?(Array) && obj.length == @types.length
    i = 0
    while i < @types.length
      if !@types[i].valid?(obj[i])
        return false
      end
      i += 1
    end
    true
  else
    false
  end
end