class T::Types::FixedHash

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

Attributes

types[R]

Public Class Methods

new(types) click to toggle source
# File lib/types/types/fixed_hash.rb, line 10
def initialize(types)
  @types = types.transform_values {|v| T::Utils.coerce(v)}
end

Public Instance Methods

describe_obj(obj) click to toggle source

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

@override Base

Calls superclass method T::Types::Base#describe_obj
# File lib/types/types/fixed_hash.rb, line 52
def describe_obj(obj)
  if obj.is_a?(Hash)
    "type #{serialize_hash(obj.transform_values(&:class))}"
  else
    super
  end
end
name() click to toggle source

@override Base

# File lib/types/types/fixed_hash.rb, line 15
def name
  serialize_hash(@types)
end
recursively_valid?(obj) click to toggle source

@override Base

# File lib/types/types/fixed_hash.rb, line 20
def recursively_valid?(obj)
  return false unless obj.is_a?(Hash)
  return false if @types.any? {|key, type| !type.recursively_valid?(obj[key])}
  return false if obj.any? {|key, _| !@types[key]}
  true
end
valid?(obj) click to toggle source

@override Base

# File lib/types/types/fixed_hash.rb, line 28
def valid?(obj)
  return false unless obj.is_a?(Hash)
  return false if @types.any? {|key, type| !type.valid?(obj[key])}
  return false if obj.any? {|key, _| !@types[key]}
  true
end

Private Instance Methods

serialize_hash(hash) click to toggle source
# File lib/types/types/fixed_hash.rb, line 62
def serialize_hash(hash)
  entries = hash.map do |(k, v)|
    if Symbol === k && ":#{k}" == k.inspect
      "#{k}: #{v}"
    else
      "#{k.inspect} => #{v}"
    end
  end

  "{#{entries.join(', ')}}"
end
subtype_of_single?(other) click to toggle source

@override Base

# File lib/types/types/fixed_hash.rb, line 36
        def subtype_of_single?(other)
  case other
  when FixedHash
    # Using `subtype_of?` here instead of == would be unsound
    @types == other.types
  else
    false
  end
end