Class: Types::Named

Inherits:
Module
  • Object
show all
Includes:
Generic
Defined in:
lib/types/named.rb

Overview

Represents a named type that may not be defined yet.

“‘ruby type = Types::Named(“CustomType”) type.parse(value) # => value (pass-through) “`

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Generic

#|

Constructor Details

#initialize(name) ⇒ Named

Initialize with a type name.



20
21
22
# File 'lib/types/named.rb', line 20

def initialize(name)
	@name = name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



25
26
27
# File 'lib/types/named.rb', line 25

def name
  @name
end

Instance Method Details

#==(other) ⇒ Object



89
90
91
# File 'lib/types/named.rb', line 89

def == other
	other.is_a?(Named) && @name == other.name
end

#absolute?Boolean

Returns:



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

def absolute?
	@name.start_with?("::")
end

#composite?Boolean

Returns:



99
100
101
# File 'lib/types/named.rb', line 99

def composite?
	false
end

#const_missing(name) ⇒ Object

Handles missing constants by creating nested Named types. This allows parsing of nested type signatures like Foo::Bar.



107
108
109
# File 'lib/types/named.rb', line 107

def const_missing(name)
	Named.new("#{@name}::#{name}")
end

#hashObject



94
95
96
# File 'lib/types/named.rb', line 94

def hash
	@name.hash
end

#inspectObject



84
85
86
# File 'lib/types/named.rb', line 84

def inspect
	"<#{self.class} #{@name}>"
end

#parse(value) ⇒ Object

Parses the input by passing it through unchanged.



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/types/named.rb', line 40

def parse(input)
	if resolved = self.resolve
		if resolved.respond_to?(:load)
			return resolved.load(input)
		elsif resolved.respond_to?(:parse)
			return resolved.parse(input)
		else
			raise ArgumentError, "Type #{@name} does not implement .load or .parse!"
		end
	else
		raise ArgumentError, "Unknown type: #{@name}"
	end
end

#relative?Boolean

Returns:



33
34
35
# File 'lib/types/named.rb', line 33

def relative?
	!absolute?
end

#resolve(relative_to: Object) ⇒ Object

Resolves the named type to the actual Ruby type if it exists.



56
57
58
59
60
# File 'lib/types/named.rb', line 56

def resolve(relative_to: Object)
	relative_to.const_get(@name)
rescue NameError
	nil
end

#to_rbsObject



75
76
77
# File 'lib/types/named.rb', line 75

def to_rbs
	@name
end

#to_sObject



80
81
82
# File 'lib/types/named.rb', line 80

def to_s
	@name
end

#to_typeObject



62
63
64
# File 'lib/types/named.rb', line 62

def to_type
	resolve(relative_to: Types)
end