Class: TinyTyping::Tester

Inherits:
Object
  • Object
show all
Defined in:
lib/tinytyping.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*types) ⇒ Tester

Returns a new instance of Tester.



54
55
56
# File 'lib/tinytyping.rb', line 54

def initialize(*types)
  @types = types
end

Class Method Details

.expect(types, value) ⇒ Object

Raises:

  • (ArgumentError)


47
48
49
50
51
# File 'lib/tinytyping.rb', line 47

def expect(types, value)
  return if expect_any(types, value)

  raise ArgumentError, "#{value.inspect} isn't #{(Array.try_convert(types) || [types]).map(&:inspect).join(' or ')}."
end

.expect_any(types, value) ⇒ Object



43
44
45
# File 'lib/tinytyping.rb', line 43

def expect_any(types, value)
  (Array.try_convert(types) || [types]).any? { |type| expect_shape(type, value) }
end

.expect_shape(type, value) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/tinytyping.rb', line 6

def expect_shape(type, value)
  case type
  when Class
    value.is_a?(type)
  when true, false, nil
    value == type
  when Array
    return false unless value.is_a?(Array)

    value.each { |val| expect(type, val) }
    true
  when Hash
    return false unless value.is_a?(Hash)

    class_key_types = []
    named_key_types = []
    type.each_key do |key|
      case key
      when Class, Array
        class_key_types << key
      else
        named_key_types << key
      end
    end
    (value.keys + named_key_types).uniq.each do |key|
      expect(class_key_types.flatten(1), key) unless type.include?(key)
      ktypes = []
      ktypes << key if named_key_types.include?(key)
      ktypes.push(*class_key_types.select { |t| expect_any(t, key) }) if value.include?(key)
      expect(ktypes.flat_map { |k| type[k] }, value[key])
    end
    true
  else
    raise TypeError, "no implicit conversion of #{type.class} into Class"
  end
end

Instance Method Details

#run!(value) ⇒ Object



58
59
60
61
# File 'lib/tinytyping.rb', line 58

def run!(value)
  self.class.expect(@types, value)
  nil
end