Class: T::Types::Union
Overview
Takes a list of types. Validates that an object matches at least one of the types.
Direct Known Subclasses
Defined Under Namespace
Modules: Private
Instance Method Summary collapse
- #build_type ⇒ Object
-
#initialize(types) ⇒ Union
constructor
Don’t use Union.new directly, use ‘Private::Pool.union_of_types` inside sorbet-runtime and `T.any` elsewhere.
-
#name ⇒ Object
overrides Base.
-
#recursively_valid?(obj) ⇒ Boolean
overrides Base.
- #types ⇒ Object
- #unwrap_nilable ⇒ Object
-
#valid?(obj) ⇒ Boolean
overrides Base.
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_type ⇒ Object
25 26 27 28 |
# File 'lib/types/types/union.rb', line 25 def build_type types nil end |
#name ⇒ Object
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
60 61 62 |
# File 'lib/types/types/union.rb', line 60 def recursively_valid?(obj) types.any? {|type| type.recursively_valid?(obj)} end |
#types ⇒ Object
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_nilable ⇒ Object
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
65 66 67 |
# File 'lib/types/types/union.rb', line 65 def valid?(obj) types.any? {|type| type.valid?(obj)} end |