class Jet::Type

Constants

MAJOR
MINOR
TINY
VERSION

Attributes

coercions[R]
name[R]
types[R]

Public Class Methods

new(name, *types, coercions: [], filter: nil, &blk) click to toggle source
# File lib/jet/type.rb, line 22
def initialize(name, *types, coercions: [], filter: nil, &blk)
  @name = name.to_sym
  @coercions = coercions.dup
  @filter = filter
  @types = Jet.type_check_each!("`types`", types, Class, Module)
  instance_eval(&blk) if block_given?
  @coercions.freeze
end
version() click to toggle source
# File lib/jet/type/version.rb, line 10
def self.version
  VERSION
end
with(type, *types, name: nil, &blk) click to toggle source
# File lib/jet/type.rb, line 9
def self.with(type, *types, name: nil, &blk)
  Jet.type_check!("`type`", type, Type)
  new(
    name || type.name,
    *[type.types, types].flatten.uniq,
    coercions: type.coercions,
    filter: type.filter,
    &blk
  )
end

Public Instance Methods

call(input) click to toggle source
# File lib/jet/type.rb, line 31
def call(input)
  return process_output(input) if type_match?(input)

  @coercions.each do |coercion|
    result = coercion.(input)
    return process_output(result.output) if result.success?
    return result if result.failure? && result != :no_coercion_match
  end

  failure(input: input)
end
filter(callable = nil, &blk) click to toggle source
# File lib/jet/type.rb, line 43
def filter(callable = nil, &blk)
  return @filter unless callable || block_given?
  @filter = Core.block_or_callable!(callable, &blk)
end
inspect() click to toggle source
# File lib/jet/type.rb, line 48
def inspect
  "#<#{self.class.name}:#{name}>"
end
maybe() click to toggle source
# File lib/jet/type.rb, line 52
def maybe
  @maybe ||= maybe? ? self : self.class.with(self, NilClass)
end
maybe?() click to toggle source
# File lib/jet/type.rb, line 56
def maybe?
  types.include?(NilClass)
end
to_sym() click to toggle source
# File lib/jet/type.rb, line 60
def to_sym
  name
end
type_match?(obj) click to toggle source
# File lib/jet/type.rb, line 64
def type_match?(obj)
  types.any? { |t| obj.is_a?(t) }
end

Private Instance Methods

coerce(at = :after, &blk) click to toggle source
# File lib/jet/type.rb, line 70
def coerce(at = :after, &blk)
  coercion = Coercion.new(&blk)
  if at == :before
    @coercions = [coercion] + coercions
  elsif at == :after
    @coercions += [coercion]
  else
    raise ArgumentError, "`at` must equal :before or :after"
  end
end
failure(error = :type_coercion_failure, **context) click to toggle source
# File lib/jet/type.rb, line 81
def failure(error = :type_coercion_failure, **context)
  Result.failure([error, name], context.merge(types: types))
end
process_output(output) click to toggle source
# File lib/jet/type.rb, line 85
def process_output(output)
  output &&= @filter ? @filter.(output) : output
  return failure(output: output) unless type_match?(output)
  Result.success(output)
end