Class: Flows::Contract::Hash

Inherits:
Flows::Contract show all
Defined in:
lib/flows/contract/hash.rb

Overview

Contract for Ruby Hash with specified contracts for keys and values.

If key contract has transformation - Hash keys will be transformed.

If value contract has transformation - Hash values will be transformed.

Examples:

sym_int_hash = Flows::Contract::Hash.new(Symbol, Integer)

sym_int_hash === { a: 1, b: 2 }
# => true

sym_int_hash === { a: 1, b: 'BBB' }
# => true

Since:

  • 0.4.0

Constant Summary collapse

CHECK_LIMIT =

Stop search for a new type mismatch in keys or values if CHECK_LIMIT errors already found.

Applied separately for keys and values.

Since:

  • 0.4.0

10
HASH_TYPE =

Since:

  • 0.4.0

CaseEq.new(::Hash)

Instance Method Summary collapse

Methods inherited from Flows::Contract

#===, #check, make, #to_proc, #transform

Constructor Details

#initialize(key_contract, value_contract) ⇒ Hash

Returns a new instance of Hash.

Parameters:

  • key_contract (Contract, Object)

    contract for keys, non-contract values will be wrapped with CaseEq

  • value_contract (Contract, Object)

    contract for values, non-contract values will be wrapped with CaseEq

Since:

  • 0.4.0



28
29
30
31
# File 'lib/flows/contract/hash.rb', line 28

def initialize(key_contract, value_contract)
  @key_contract = to_contract(key_contract)
  @value_contract = to_contract(value_contract)
end

Instance Method Details

#check!(other) ⇒ Object

Since:

  • 0.4.0



33
34
35
36
37
38
39
40
41
42
# File 'lib/flows/contract/hash.rb', line 33

def check!(other)
  HASH_TYPE.check!(other)

  unless other.keys.all?(&@key_contract) && other.values.all?(&@value_contract)
    value_error = report_error(other)
    raise Error.new(other, value_error)
  end

  true
end

#transform!(other) ⇒ Object

Since:

  • 0.4.0



44
45
46
47
48
49
50
# File 'lib/flows/contract/hash.rb', line 44

def transform!(other)
  check!(other)

  other
    .transform_keys { |key| @key_contract.transform!(key) }
    .transform_values { |value| @value_contract.transform!(value) }
end