Sha256: 2d25d86acacbfed5c9046d293f18d605419fd32b2ed903160f066b6df6fb681e

Contents?: true

Size: 1.58 KB

Versions: 341

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true
# typed: true

module T::Types
  # Takes a list of types. Validates that an object matches at least one of the types.
  class Union < Base
    attr_reader :types

    def initialize(types)
      @types = types.flat_map do |type|
        if type.is_a?(Union)
          # Simplify nested unions (mostly so `name` returns a nicer value)
          type.types
        else
          T::Utils.coerce(type)
        end
      end.uniq
    end

    # @override Base
    def name
      type_shortcuts(@types)
    end

    private 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

    # @override Base
    def valid?(obj)
      @types.each do |type|
        return true if type.valid?(obj)
      end

      false
    end

    # @override Base
    private def subtype_of_single?(other)
      raise "This should never be reached if you're going through `subtype_of?` (and you should be)"
    end

  end
end

Version data entries

341 entries across 341 versions & 1 rubygems

Version Path
sorbet-runtime-0.4.4564 lib/types/types/union.rb
sorbet-runtime-0.4.4563 lib/types/types/union.rb
sorbet-runtime-0.4.4562 lib/types/types/union.rb
sorbet-runtime-0.4.4561 lib/types/types/union.rb
sorbet-runtime-0.4.4560 lib/types/types/union.rb
sorbet-runtime-0.4.4559 lib/types/types/union.rb
sorbet-runtime-0.4.4558 lib/types/types/union.rb
sorbet-runtime-0.4.4557 lib/types/types/union.rb
sorbet-runtime-0.4.4556 lib/types/types/union.rb
sorbet-runtime-0.4.4555 lib/types/types/union.rb
sorbet-runtime-0.4.4554 lib/types/types/union.rb
sorbet-runtime-0.4.4553 lib/types/types/union.rb
sorbet-runtime-0.4.4552 lib/types/types/union.rb
sorbet-runtime-0.4.4551 lib/types/types/union.rb
sorbet-runtime-0.4.4550 lib/types/types/union.rb
sorbet-runtime-0.4.4549 lib/types/types/union.rb
sorbet-runtime-0.4.4548 lib/types/types/union.rb
sorbet-runtime-0.4.4547 lib/types/types/union.rb
sorbet-runtime-0.4.4544 lib/types/types/union.rb
sorbet-runtime-0.4.4543 lib/types/types/union.rb