Class: T::Private::Types::SimplePairUnion
- Inherits:
-
Types::Union
- Object
- Types::Base
- Types::Union
- T::Private::Types::SimplePairUnion
- Defined in:
- lib/types/private/types/simple_pair_union.rb
Overview
Specialization of Union for the common case of the union of two simple types.
This covers e.g. T.nilable(SomeModule), T.any(Integer, Float), and T::Boolean.
Defined Under Namespace
Classes: DuplicateType
Instance Method Summary collapse
-
#initialize(type_a, type_b) ⇒ SimplePairUnion
constructor
A new instance of SimplePairUnion.
- #recursively_valid?(obj) ⇒ Boolean
- #types ⇒ Object
-
#unwrap_nilable ⇒ Object
overrides Union.
- #valid?(obj) ⇒ Boolean
Methods inherited from Types::Union
Methods inherited from Types::Base
#==, #describe_obj, #error_message_for_obj, #error_message_for_obj_recursive, #hash, method_added, #subtype_of?, #to_s, #validate!
Constructor Details
#initialize(type_a, type_b) ⇒ SimplePairUnion
Returns a new instance of SimplePairUnion.
12 13 14 15 16 17 18 19 |
# File 'lib/types/private/types/simple_pair_union.rb', line 12 def initialize(type_a, type_b) if type_a == type_b raise DuplicateType.new("#{type_a} == #{type_b}") end @raw_a = type_a.raw_type @raw_b = type_b.raw_type end |
Instance Method Details
#recursively_valid?(obj) ⇒ Boolean
22 23 24 |
# File 'lib/types/private/types/simple_pair_union.rb', line 22 def recursively_valid?(obj) obj.is_a?(@raw_a) || obj.is_a?(@raw_b) end |
#types ⇒ Object
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/types/private/types/simple_pair_union.rb', line 32 def types # We reconstruct the simple types rather than just storing them because # (1) this is normally not a hot path and (2) we want to keep the instance # variable count <= 3 so that we can fit in a 40 byte heap entry along # with object headers. @types ||= [ T::Types::Simple::Private::Pool.type_for_module(@raw_a), T::Types::Simple::Private::Pool.type_for_module(@raw_b), ] end |
#unwrap_nilable ⇒ Object
overrides Union
44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/types/private/types/simple_pair_union.rb', line 44 def unwrap_nilable a_nil = @raw_a.equal?(NilClass) b_nil = @raw_b.equal?(NilClass) if a_nil return types[1] end if b_nil return types[0] end nil end |
#valid?(obj) ⇒ Boolean
27 28 29 |
# File 'lib/types/private/types/simple_pair_union.rb', line 27 def valid?(obj) obj.is_a?(@raw_a) || obj.is_a?(@raw_b) end |