Class: T::Types::FixedHash
Overview
Takes a hash of types. Validates each item in a hash using the type in the same position in the list.
Instance Method Summary collapse
- #build_type ⇒ Object
-
#describe_obj(obj) ⇒ Object
This gives us better errors, e.g.: ‘Expected String, got TrueClass` instead of `Expected String, got Hash`.
-
#initialize(types) ⇒ FixedHash
constructor
A new instance of FixedHash.
-
#name ⇒ Object
overrides Base.
-
#recursively_valid?(obj) ⇒ Boolean
overrides Base.
- #types ⇒ Object
-
#valid?(obj) ⇒ Boolean
overrides Base.
Methods inherited from Base
#==, #error_message_for_obj, #error_message_for_obj_recursive, #hash, method_added, #subtype_of?, #to_s, #validate!
Constructor Details
#initialize(types) ⇒ FixedHash
Returns a new instance of FixedHash.
8 9 10 |
# File 'lib/types/types/fixed_hash.rb', line 8 def initialize(types) @inner_types = types end |
Instance Method Details
#build_type ⇒ Object
16 17 18 19 |
# File 'lib/types/types/fixed_hash.rb', line 16 def build_type types nil end |
#describe_obj(obj) ⇒ Object
This gives us better errors, e.g.: ‘Expected String, got TrueClass` instead of `Expected String, got Hash`.
overrides Base
95 96 97 98 99 100 101 |
# File 'lib/types/types/fixed_hash.rb', line 95 def describe_obj(obj) if obj.is_a?(Hash) "type #{serialize_hash(obj.transform_values(&:class))}" else super end end |
#name ⇒ Object
overrides Base
22 23 24 |
# File 'lib/types/types/fixed_hash.rb', line 22 def name serialize_hash(types) end |
#recursively_valid?(obj) ⇒ Boolean
overrides Base
27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/types/types/fixed_hash.rb', line 27 def recursively_valid?(obj) return false unless obj.is_a?(Hash) field_types = types field_types.each_pair do |key, type| return false unless type.recursively_valid?(obj[key]) end # Pigeonhole: more entries than declared keys guarantees an undeclared key. return false if obj.size > field_types.size obj.each_key do |key| return false unless field_types.key?(key) end true end |
#types ⇒ Object
12 13 14 |
# File 'lib/types/types/fixed_hash.rb', line 12 def types @types ||= @inner_types.transform_values { |v| T::Utils.coerce(v) } end |
#valid?(obj) ⇒ Boolean
overrides Base
42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/types/types/fixed_hash.rb', line 42 def valid?(obj) return false unless obj.is_a?(Hash) field_types = types field_types.each_pair do |key, type| return false unless type.valid?(obj[key]) end # Pigeonhole: more entries than declared keys guarantees an undeclared key. return false if obj.size > field_types.size obj.each_key do |key| return false unless field_types.key?(key) end true end |