Sha256: 1656ee742c4dad9397bc42b1dafb40321178f805ae3476328541a9851257b880

Contents?: true

Size: 1.27 KB

Versions: 530

Compression:

Stored size: 1.27 KB

Contents

# frozen_string_literal: true
# typed: true

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

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

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

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

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

530 entries across 530 versions & 1 rubygems

Version Path
sorbet-runtime-0.5.5551 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5549 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5544 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5532 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5525 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5519 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5516 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5510 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5507 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5505 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5501 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5497 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5480 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5478 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5472 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5470 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5469 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5468 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5461 lib/types/types/fixed_hash.rb
sorbet-runtime-0.5.5460 lib/types/types/fixed_hash.rb