class Type

Converts input values to a specific application type.

Definitions

def self.expected(type)

Resolve the expected output type of a converter.

Implementation

def self.expected(type)
	if type.respond_to?(:type)
		return type.type
	else
		return type
	end
end

def initialize(type, &converter)

Initialize a type converter.

Signature

parameter type Object

The expected converted type.

yields {|value| ...}

The conversion operation.

Implementation

def initialize(type, &converter)
	@type = type
	@converter = converter
end

attr :type

The expected converted type.

def call(value)

Convert a value to the declared type.

Signature

parameter value Object

The input value.

returns Object

The converted value.

raises TypeError

If the value cannot be converted.

Implementation

def call(value)
	# Preserve values which already have the expected type:
	if @type === value
		return value
	end
	
	if @converter
		value = @converter.call(value)
		
		# Ensure converters produce the type they declare:
		if @type === value
			return value
		end
	end
	
	raise TypeError, "Could not convert #{value.inspect} to #{@type}!"
end