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 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.



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

def initialize(types)
  @inner_types = types
end

Instance Method Details

#build_typeObject



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

def build_type
  types
  nil
end

#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



93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/types/types/fixed_array.rb', line 93

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



23
24
25
# File 'lib/types/types/fixed_array.rb', line 23

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

#recursively_valid?(obj) ⇒ Boolean

overrides Base

Returns:



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/types/types/fixed_array.rb', line 28

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

#typesObject



13
14
15
# File 'lib/types/types/fixed_array.rb', line 13

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

#valid?(obj) ⇒ Boolean

overrides Base

Returns:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/types/types/fixed_array.rb', line 44

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