class Yarrow::Schema::Types::TypeClass

Attributes

accepts[R]
unit[R]

Public Class Methods

new(unit_type=nil) click to toggle source
# File lib/yarrow/schema/types.rb, line 33
def initialize(unit_type=nil)
  @unit = unit_type
  @accepts = {}
end
of(unit_type) click to toggle source
# File lib/yarrow/schema/types.rb, line 27
def self.of(unit_type)
  new(unit_type)
end

Public Instance Methods

accept(type, constructor=:new, options=nil) click to toggle source
# File lib/yarrow/schema/types.rb, line 42
def accept(type, constructor=:new, options=nil)
  accepts[type] = if options.nil?
    [constructor]
  else
    [constructor, options]
  end

  self
end
cast(input) click to toggle source
# File lib/yarrow/schema/types.rb, line 91
def cast(input)
  return coerce(input) if should_coerce?(input)
  check(input)
end
check_instance_of!(input) click to toggle source
# File lib/yarrow/schema/types.rb, line 67
def check_instance_of!(input)
  unless input.instance_of?(unit)
    raise CastError.instance_of(input.class, unit)
  end
end
check_kind_of!(input) click to toggle source
# File lib/yarrow/schema/types.rb, line 73
def check_kind_of!(input)
  unless input.kind_of?(unit)
    raise CastError.kind_of(input.class, unit)
  end
end
check_respond_to_all!(input, methods) click to toggle source
# File lib/yarrow/schema/types.rb, line 85
def check_respond_to_all!(input, methods)
  unless methods.all? { |m| input.respond_to?(m) }
    raise CastError.respond_to_all(input.class, methods)
  end
end
check_respond_to_any!(input, methods) click to toggle source
# File lib/yarrow/schema/types.rb, line 79
def check_respond_to_any!(input, methods)
  unless methods.any? { |m| input.respond_to?(m) }
    raise CastError.respond_to_any(input.class, methods)
  end
end
coerce(input) click to toggle source
# File lib/yarrow/schema/types.rb, line 56
def coerce(input)
  constructor, options = accepts[input.class]

  # TODO: should we clone all input so copy is stored rather than ref?
  if options.nil?
    unit.send(constructor, input)
  else
    unit.send(constructor, input, options.clone)
  end
end
should_coerce?(input) click to toggle source
# File lib/yarrow/schema/types.rb, line 52
def should_coerce?(input)
  accepts.key?(input.class)
end
|(rhs_opt) click to toggle source
# File lib/yarrow/schema/types.rb, line 38
def |(rhs_opt)
  Union.new(self, rhs_opt)
end