Class: T::Types::TypedEnumerable

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

Overview

Note: All subclasses of Enumerable should add themselves to the ‘case` statement below in `describe_obj` in order to get better error messages.

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(type) ⇒ TypedEnumerable

Returns a new instance of TypedEnumerable.



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

def initialize(type)
  @type = T::Utils.coerce(type)
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



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

def type
  @type
end

Instance Method Details

#describe_obj(obj) ⇒ Object



85
86
87
88
# File 'lib/types/types/typed_enumerable.rb', line 85

def describe_obj(obj)
  return super unless obj.is_a?(Enumerable)
  type_from_instance(obj).name
end

#nameObject



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

def name
  "T::Enumerable[#{@type.name}]"
end

#valid?(obj) ⇒ Boolean

Returns:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/types/types/typed_enumerable.rb', line 21

def valid?(obj)
  return false unless obj.is_a?(Enumerable)
  case obj
  when Array
    begin
      it = 0
      while it < obj.count
        return false unless @type.valid?(obj[it])
        it += 1
      end
      return true
    end
  when Hash
    return false unless @type.is_a?(FixedArray)
    types = @type.types
    return false if types.count != 2
    key_type = types[0]
    value_type = types[1]
    obj.each_pair do |key, val|
      # Some objects (I'm looking at you Rack::Utils::HeaderHash) don't
      # iterate over a [key, value] array, so we can't juse use the @type.valid?(v)
      return false if !key_type.valid?(key) || !value_type.valid?(val)
    end
    return true
  when Enumerator::Lazy
    # Users don't want these walked
    return true
  when Enumerator
    obj.each do |elem|
      return false unless @type.valid?(elem)
    end
    return true
  when Range
    @type.valid?(obj.first) && @type.valid?(obj.last)
  when Set
    obj.each do |item|
      return false unless @type.valid?(item)
    end

    return true
  else
    # We don't check the enumerable since it isn't guaranteed to be
    # rewindable (e.g. STDIN) and it may be expensive to enumerate
    # (e.g. an enumerator that makes an HTTP request)"
    true
  end
end