class Dry::Types::Map

@api public
# Dry::Types::MapError: 11 violates constraints (lteq?(10, 11) failed)
type.(11 => ‘wrong’)
# AND lteq?(10, “1”) failed)
# AND gteq?(1, “1”)
# Dry::Types::MapError: “1” violates constraints (type?(Integer, “1”)
type.(‘1’ => ‘wrong’)
# => {1 => ‘right’}
type.(1 => ‘right’)<br><br>)<br>Dry::Types[‘string’]<br>Dry::Types.constrained(gteq: 1, lteq: 10),
type = Dry::Types.map(
@example
Homogeneous mapping. It describes a hash with unknown keys that match a certain type.

def assert_primitive(input)

def assert_primitive(input)
  if primitive?(input)
    yield
  else
    failure(input, CoercionError.new("#{input.inspect} must be an instance of #{primitive}"))
  end
end

def call_safe(hash) = try(hash) { return yield }.input

Other tags:
    Api: - private

Returns:
  • (Hash) -

Parameters:
  • hash (Hash) --
def call_safe(hash) = try(hash) { return yield }.input

def call_unsafe(hash)

Other tags:
    Api: - private

Returns:
  • (Hash) -

Parameters:
  • hash (Hash) --
def call_unsafe(hash)
  try(hash) { |failure|
    raise MapError, failure.error.message
  }.input
end

def coerce(input)

Other tags:
    Api: - private
def coerce(input)
  assert_primitive(input) do
    output = {}
    failures = []
    input.each do |k, v|
      res_k = key_type.try(k)
      res_v = value_type.try(v)
      if res_k.failure?
        failures << res_k.error
      elsif output.key?(res_k.input)
        failures << CoercionError.new("duplicate coerced hash key #{res_k.input.inspect}")
      elsif res_v.failure?
        failures << res_v.error
      else
        output[res_k.input] = res_v.input
      end
    end
    if failures.empty?
      success(output)
    else
      failure(input, MultipleError.new(failures))
    end
  end
end

def constrained? = value_type.constrained?

Other tags:
    Api: - public

Returns:
  • (Boolean) -
def constrained? = value_type.constrained?

def initialize(primitive, key_type: Types["any"], value_type: Types["any"], meta: EMPTY_HASH)

def initialize(primitive, key_type: Types["any"], value_type: Types["any"], meta: EMPTY_HASH)
  super
end

def key_type = options[:key_type]

Other tags:
    Api: - public

Returns:
  • (Type) -
def key_type = options[:key_type]

def name = "Map"

Other tags:
    Api: - public

Returns:
  • (String) -
def name = "Map"

def to_ast(meta: true)

Other tags:
    Api: - public

Returns:
  • (Array) - An AST representation

Parameters:
  • meta (Boolean) -- Whether to dump the meta to the AST
def to_ast(meta: true)
  [:map,
   [key_type.to_ast(meta: true),
    value_type.to_ast(meta: true),
    meta ? self.meta : EMPTY_HASH]]
end

def try(hash)

Other tags:
    Api: - public

Returns:
  • (Result) -

Parameters:
  • hash (Hash) --
def try(hash)
  result = coerce(hash)
  return result if result.success? || !block_given?
  yield(result)
end

def value_type = options[:value_type]

Other tags:
    Api: - public

Returns:
  • (Type) -
def value_type = options[:value_type]