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 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.



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

def initialize(types)
  @inner_types = types
end

Instance Method Details

#build_typeObject



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

def build_type
  types
  nil
end

#nameObject

overrides Base



31
32
33
34
# File 'lib/types/types/union.rb', line 31

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:



60
61
62
# File 'lib/types/types/union.rb', line 60

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

#typesObject



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

def types
  @types ||= @inner_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

#unwrap_nilableObject



74
75
76
77
78
79
80
81
82
83
# File 'lib/types/types/union.rb', line 74

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:



65
66
67
# File 'lib/types/types/union.rb', line 65

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