Class: Uinit::Type::HashOf

Inherits:
Base
  • Object
show all
Defined in:
lib/uinit/type/hash_of.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#==, [], #is!, #to_s, #trace!, #type_error!

Methods included from Operators

#&, #|

Constructor Details

#initialize(schema, strict: false) ⇒ HashOf

Returns a new instance of HashOf.

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/uinit/type/hash_of.rb', line 14

def initialize(schema, strict: false)
  super()

  raise ArgumentError, 'schema must be a Hash' unless self.class.from?(schema)

  @schema =
    schema.transform_values do |type|
      Type.from(type)
    end

  @strict = !!strict
end

Instance Attribute Details

#schemaObject (readonly)

Returns the value of attribute schema.



27
28
29
# File 'lib/uinit/type/hash_of.rb', line 27

def schema
  @schema
end

#strictObject (readonly)

Returns the value of attribute strict.



27
28
29
# File 'lib/uinit/type/hash_of.rb', line 27

def strict
  @strict
end

Class Method Details

.from(schema) ⇒ Object



10
11
12
# File 'lib/uinit/type/hash_of.rb', line 10

def self.from(schema)
  new(schema) if from?(schema)
end

.from?(schema) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/uinit/type/hash_of.rb', line 6

def self.from?(schema)
  schema.is_a?(Hash)
end

Instance Method Details

#check!(value, depth) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/uinit/type/hash_of.rb', line 44

def check!(value, depth)
  type_error!("#{value.inspect} must be a Hash", depth) unless value.is_a?(Hash)

  schema.each do |key, type|
    type.check!(value[key], depth + 1)
  rescue Error => e
    trace!(e, "[#{key.inspect}]")
  end

  value
end

#inspectObject



56
57
58
# File 'lib/uinit/type/hash_of.rb', line 56

def inspect
  "#{super}[#{schema.inspect}]"
end

#is?(value) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/uinit/type/hash_of.rb', line 29

def is?(value)
  return false unless value.is_a?(Hash)

  is =
    schema.all? do |key, type|
      type.is?(value[key])
    end

  return is unless strict

  extra = value.keys - schema

  extra.empty?
end