Class: YardTypes::TupleType

Inherits:
CollectionType show all
Defined in:
lib/yard_types/types.rb

Overview

TODO:

The current implementation of type checking here requires that the collection respond to both length and []; this may not be ideal.

A TupleType is specified with the syntax (Some, Types, #here), and indicates that the contents of the collection must be exactly that size, and each element must be of the exact type specified for that index.

Instance Attribute Summary

Attributes inherited from CollectionType

#types

Attributes inherited from Type

#name

Instance Method Summary collapse

Methods inherited from Type

for

Constructor Details

#initialize(name, types) ⇒ TupleType

Returns a new instance of TupleType.



214
215
216
217
# File 'lib/yard_types/types.rb', line 214

def initialize(name, types)
  @name  = name == '<generic-tuple>' ? nil : name
  @types = types
end

Instance Method Details

#check(obj) ⇒ Boolean

Returns true if the collection’s length is exactly the length of the expected types, and each element with the collection is of the type specified for that index by types.

Parameters:

  • obj (Object)

    Any object.

Returns:

  • (Boolean)

    true if the collection’s length is exactly the length of the expected types, and each element with the collection is of the type specified for that index by types.



228
229
230
231
232
233
234
235
236
237
# File 'lib/yard_types/types.rb', line 228

def check(obj)
  return false unless name.nil? || KindType.new(name).check(obj)
  return false unless obj.respond_to?(:length) && obj.respond_to?(:[])
  return false unless obj.length == types.length

  enum = types.to_enum
  enum.with_index.all? do |t, i|
    t.check(obj[i])
  end
end

#to_sString

Returns a YARD type string describing this type.

Returns:

  • (String)

    a YARD type string describing this type.



220
221
222
# File 'lib/yard_types/types.rb', line 220

def to_s
  "%s(%s)" % [name, types.map(&:to_s).join(', ')]
end