Class: Types::Any

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

Overview

Represents a union of multiple types. The first type to match the input is used. If no types are specified, this matches any type or value.

“‘ruby type = Types::Any(Types::String, Types::Integer) “`

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(types) ⇒ Any

Initialize the instance with an array of types.



17
18
19
# File 'lib/types/any.rb', line 17

def initialize(types)
	@types = types
end

Class Method Details

.parse(value) ⇒ Object

Accepts any value as a class type.



57
58
59
# File 'lib/types/any.rb', line 57

def self.parse(value)
	value
end

Instance Method Details

#composite?Boolean

Returns:



28
29
30
# File 'lib/types/any.rb', line 28

def composite?
	@types.any?(&:composite?)
end

#parse(input) ⇒ Object

Parses the input using the listed types in order, returning the first one that succeeds.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/types/any.rb', line 36

def parse(input)
	# If there are no types, we can just return the input.
	return input if @types.empty?
	
	# We need to track the last error, because we want to raise the last error that occurred, if any:
	last_error = nil
	
	@types.each do |type|
		return type.parse(input)
	rescue => error
		last_error = error
	end
	
	if last_error
		raise last_error
	else
		raise ArgumentError, "Unable to parse input #{input.inspect}!"
	end
end

#to_rbsObject

Returns the RBS type string for the union of the listed types. If there are no types, it returns ‘untyped`.



72
73
74
75
76
77
78
# File 'lib/types/any.rb', line 72

def to_rbs
	if @types.empty?
		"untyped"
	else
		@types.map(&:to_rbs).join(" | ")
	end
end

#to_sObject



62
63
64
65
66
67
68
# File 'lib/types/any.rb', line 62

def to_s
	if @types.empty?
		"Any()"
	else
		"#{@types.join(' | ')}"
	end
end

#|(other) ⇒ Object



23
24
25
# File 'lib/types/any.rb', line 23

def | other
	self.class.new([*@types, other])
end