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, #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”.



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

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



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

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

#valid?(obj) ⇒ Boolean

Returns:



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

def valid?(obj)
  obj.is_a?(Array) && obj.length == @types.length &&
    obj.zip(@types).all? {|item, type| type.valid?(item)}
end