Class: T::Types::FixedHash

Inherits:
Base
  • Object
show all
Defined in:
lib/types/types/fixed_hash.rb

Overview

Takes a hash of types. Validates each item in an hash using the type in the same position in the list.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#==, #error_message_for_obj, #hash, method_added, #subtype_of?, #to_s, #validate!

Constructor Details

#initialize(types) ⇒ FixedHash

Returns a new instance of FixedHash.



10
11
12
# File 'lib/types/types/fixed_hash.rb', line 10

def initialize(types)
  @types = types.each_with_object({}) {|(k, v), h| h[k] = T::Utils.coerce(v)}
end

Instance Attribute Details

#typesObject (readonly)

Returns the value of attribute types.



8
9
10
# File 'lib/types/types/fixed_hash.rb', line 8

def types
  @types
end

Instance Method Details

#describe_obj(obj) ⇒ Object

This gives us better errors, e.g.: “Expected String, got TrueClass” instead of “Expected String, got Hash”.



51
52
53
54
55
56
57
# File 'lib/types/types/fixed_hash.rb', line 51

def describe_obj(obj)
  if obj.is_a?(Hash)
    "type {#{obj.map {|(k, v)| "#{k}: #{v.class}"}.join(', ')}}"
  else
    super
  end
end

#nameObject



15
16
17
# File 'lib/types/types/fixed_hash.rb', line 15

def name
  "{#{@types.map {|(k, v)| "#{k}: #{v}"}.join(', ')}}"
end

#valid?(obj) ⇒ Boolean

Returns:



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/types/types/fixed_hash.rb', line 20

def valid?(obj)
  return false unless obj.is_a?(Hash)

  @types.each do |key, type|
    return false unless type.valid?(obj[key])
  end

  obj.each_key do |key|
    return false unless @types[key]
  end

  true
end