class T::Types::Union

Takes a list of types. Validates that an object matches at least one of the types.

Attributes

types[R]

Public Class Methods

new(types) click to toggle source
# File lib/types/types/union.rb, line 9
def initialize(types)
  @types = types.flat_map do |type|
    type = T::Utils.coerce(type)
    if type.is_a?(Union)
      # Simplify nested unions (mostly so `name` returns a nicer value)
      type.types
    else
      type
    end
  end.uniq
end

Public Instance Methods

name() click to toggle source

@override Base

# File lib/types/types/union.rb, line 22
def name
  type_shortcuts(@types)
end
recursively_valid?(obj) click to toggle source

@override Base

# File lib/types/types/union.rb, line 46
def recursively_valid?(obj)
  @types.any? {|type| type.recursively_valid?(obj)}
end
valid?(obj) click to toggle source

@override Base

# File lib/types/types/union.rb, line 51
def valid?(obj)
  @types.any? {|type| type.valid?(obj)}
end

Private Instance Methods

subtype_of_single?(other) click to toggle source

@override Base

# File lib/types/types/union.rb, line 56
        def subtype_of_single?(other)
  raise "This should never be reached if you're going through `subtype_of?` (and you should be)"
end
type_shortcuts(types) click to toggle source
# File lib/types/types/union.rb, line 26
        def type_shortcuts(types)
  if types.size == 1
    return types[0].name
  end
  nilable = T::Utils.coerce(NilClass)
  trueclass = T::Utils.coerce(TrueClass)
  falseclass = T::Utils.coerce(FalseClass)
  if types.any? {|t| t == nilable}
    remaining_types = types.reject {|t| t == nilable}
    "T.nilable(#{type_shortcuts(remaining_types)})"
  elsif types.any? {|t| t == trueclass} && types.any? {|t| t == falseclass}
    remaining_types = types.reject {|t| t == trueclass || t == falseclass}
    type_shortcuts([T::Private::Types::StringHolder.new("T::Boolean")] + remaining_types)
  else
    names = types.map(&:name).compact.sort
    "T.any(#{names.join(', ')})"
  end
end