Class: Yarrow::Schema::Types::TypeClass

Inherits:
Object
  • Object
show all
Defined in:
lib/yarrow/schema/types.rb

Direct Known Subclasses

Any, Instance, Interface, Kind, List, Map

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(unit_type = nil) ⇒ TypeClass



29
30
31
32
# File 'lib/yarrow/schema/types.rb', line 29

def initialize(unit_type=nil)
  @unit = unit_type
  @accepts = {}
end

Instance Attribute Details

#acceptsObject (readonly)

Returns the value of attribute accepts.



27
28
29
# File 'lib/yarrow/schema/types.rb', line 27

def accepts
  @accepts
end

#unitObject (readonly)

Returns the value of attribute unit.



27
28
29
# File 'lib/yarrow/schema/types.rb', line 27

def unit
  @unit
end

Class Method Details

.of(unit_type) ⇒ Object



23
24
25
# File 'lib/yarrow/schema/types.rb', line 23

def self.of(unit_type)
  new(unit_type)
end

Instance Method Details

#accept(type, constructor = :new) ⇒ Object



34
35
36
37
# File 'lib/yarrow/schema/types.rb', line 34

def accept(type, constructor=:new)
  accepts[type] = constructor
  self
end

#cast(input) ⇒ Object



72
73
74
75
# File 'lib/yarrow/schema/types.rb', line 72

def cast(input)
  return coerce(input) if should_coerce?(input)
  check(input)
end

#check_instance_of!(input) ⇒ Object



48
49
50
51
52
# File 'lib/yarrow/schema/types.rb', line 48

def check_instance_of!(input)
  unless input.instance_of?(unit)
    raise CastError.instance_of(input.class, unit)
  end
end

#check_kind_of!(input) ⇒ Object



54
55
56
57
58
# File 'lib/yarrow/schema/types.rb', line 54

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) ⇒ Object



66
67
68
69
70
# File 'lib/yarrow/schema/types.rb', line 66

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) ⇒ Object



60
61
62
63
64
# File 'lib/yarrow/schema/types.rb', line 60

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) ⇒ Object



43
44
45
46
# File 'lib/yarrow/schema/types.rb', line 43

def coerce(input)
  constructor = accepts[input.class]
  unit.send(constructor, input)
end

#should_coerce?(input) ⇒ Boolean



39
40
41
# File 'lib/yarrow/schema/types.rb', line 39

def should_coerce?(input)
  accepts.key?(input.class)
end