Class: Literal::VariantType

Inherits:
Generic
  • Object
show all
Defined in:
lib/literal/variant_type.rb

Instance Method Summary collapse

Methods included from Modifiers

extended

Constructor Details

#initialize(*types) ⇒ VariantType

Returns a new instance of VariantType.



4
5
6
# File 'lib/literal/variant_type.rb', line 4

def initialize(*types)
	@types = types
end

Instance Method Details

#exception_typesObject (private)



57
58
59
# File 'lib/literal/variant_type.rb', line 57

def exception_types
	@types.select { |type| Class === type && type < Exception }
end

#inspectObject



8
# File 'lib/literal/variant_type.rb', line 8

def inspect = "Literal::Variant(#{@types.inspect})"

#new(value = Literal::Null) ⇒ Object

Create a new variant



13
14
15
16
17
18
19
20
21
# File 'lib/literal/variant_type.rb', line 13

def new(value = Literal::Null)
	if Literal::Null != value
		Literal::Variant.new(value, *@types)
	elsif block_given?
		Literal::Variant.new(yield, *@types)
	else
		raise Literal::ArgumentError, "A value or block must be provided."
	end
end

#rescue(*exceptions) ⇒ Object

Will rescue and return given exceptions, as long as they are members of the variant union.



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

def rescue(*exceptions)
	exceptions.each do |exception|
		unless Class === exception && exception < Exception
			raise Literal::TypeError, "The exception must be a subclass of Exception."
		end

		unless @types.include?(exception)
			raise Literal::ArgumentError, "The exception must be a member of the variant union."
		end
	end

	begin
		value = yield
	rescue *exceptions => e
		value = e
	end

	Literal::Variant.new(value, *@types)
end

#tryObject

Will rescue and return any exception that is a member of the variant union.



24
25
26
27
28
29
30
31
32
# File 'lib/literal/variant_type.rb', line 24

def try
	begin
		value = yield
	rescue *exception_types => e
		value = e
	end

	Literal::Variant.new(value, *@types)
end