Sha256: f7d38275bc044c4179f7f7a1e852328d59be32c22db16721242e31c8e3393c5f

Contents?: true

Size: 1.46 KB

Versions: 29

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true
# typed: true

module T::Types
  # Takes a hash of types. Validates each item in a hash using the type in the same position
  # in the list.
  class FixedHash < Base
    attr_reader :types

    def initialize(types)
      @types = types.transform_values {|v| T::Utils.coerce(v)}
    end

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

    # @override Base
    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

    # @override Base
    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

    # @override Base
    private 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

    # This gives us better errors, e.g.:
    # "Expected {a: String}, got {a: TrueClass}"
    # instead of
    # "Expected {a: String}, got Hash".
    #
    # @override Base
    def describe_obj(obj)
      if obj.is_a?(Hash)
        "type {#{obj.map {|(k, v)| "#{k}: #{v.class}"}.join(', ')}}"
      else
        super
      end
    end
  end
end

Version data entries

29 entries across 29 versions & 1 rubygems

Version Path
sorbet-runtime-0.5.6415 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6412 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6408 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6407 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6405 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6403 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6401 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6400 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6398 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6397 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6395 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6393 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6391 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6389 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6388 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6386 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6385 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6382 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6380 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.6376 lib/types/types/fixed_hash.rb