Class: T::Types::Union

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

Overview

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

Direct Known Subclasses

Private::Types::SimplePairUnion

Defined Under Namespace

Modules: Private

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#==, #describe_obj, #error_message_for_obj, #error_message_for_obj_recursive, #hash, method_added, #subtype_of?, #to_s, #validate!

Constructor Details

#initialize(types) ⇒ Union

Don’t use Union.new directly, use ‘Private::Pool.union_of_types` inside sorbet-runtime and `T.any` elsewhere.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/types/types/union.rb', line 11

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

Instance Attribute Details

#typesObject (readonly)

Returns the value of attribute types.



7
8
9
# File 'lib/types/types/union.rb', line 7

def types
  @types
end

Instance Method Details

#nameObject

overrides Base



24
25
26
27
# File 'lib/types/types/union.rb', line 24

def name
  # Use the attr_reader here so we can override it in SimplePairUnion
  type_shortcuts(types)
end

#recursively_valid?(obj) ⇒ Boolean

overrides Base

Returns:



53
54
55
# File 'lib/types/types/union.rb', line 53

def recursively_valid?(obj)
  @types.any? {|type| type.recursively_valid?(obj)}
end

#unwrap_nilableObject



67
68
69
70
71
72
73
74
75
76
# File 'lib/types/types/union.rb', line 67

def unwrap_nilable
  non_nil_types = types.reject {|t| t == T::Utils::Nilable::NIL_TYPE}
  return nil if types.length == non_nil_types.length
  case non_nil_types.length
  when 0 then nil
  when 1 then non_nil_types.first
  else
    T::Types::Union::Private::Pool.union_of_types(non_nil_types[0], non_nil_types[1], non_nil_types[2..-1])
  end
end

#valid?(obj) ⇒ Boolean

overrides Base

Returns:



58
59
60
# File 'lib/types/types/union.rb', line 58

def valid?(obj)
  @types.any? {|type| type.valid?(obj)}
end