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 included from OrList

#or_list

Methods inherited from Type

for

Constructor Details

#initialize(name, types) ⇒ TupleType

Returns a new instance of TupleType


256
257
258
259
# File 'lib/yard_types/types.rb', line 256

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.


278
279
280
281
282
283
284
285
286
287
# File 'lib/yard_types/types.rb', line 278

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

#descriptionString

Returns an English phrase describing this type.

Returns:

  • (String)

    an English phrase describing this type.


267
268
269
270
271
272
# File 'lib/yard_types/types.rb', line 267

def description
  kind = name || 'tuple'
  article = kind[0] =~ /[aeiou]/i ? 'an' : 'a'
  contents = types.map(&:description).join(', ')
  "#{article} #{kind} containing (#{contents})"
end

#to_sString

Returns a YARD type string describing this type.

Returns:

  • (String)

    a YARD type string describing this type.


262
263
264
# File 'lib/yard_types/types.rb', line 262

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