Class: Contracts::Builtin::StrictHash

Inherits:
CallableClass show all
Defined in:
lib/contracts-ruby2/lib/contracts/builtin_contracts.rb,
lib/contracts-ruby3/lib/contracts/builtin_contracts.rb

Overview

Use this to specify the Hash characteristics. This contracts fails if there are any extra keys that don’t have contracts on them. Example: StrictHash[{ a: String, b: Bool }]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from CallableClass

[]

Constructor Details

#initialize(contract_hash) ⇒ StrictHash

Returns a new instance of StrictHash.



402
403
404
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 402

def initialize(contract_hash)
  @contract_hash = contract_hash
end

Instance Attribute Details

#contract_hashObject (readonly)

Returns the value of attribute contract_hash.



400
401
402
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 400

def contract_hash
  @contract_hash
end

Instance Method Details

#valid?(arg) ⇒ Boolean

Returns:

  • (Boolean)


406
407
408
409
410
411
412
413
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 406

def valid?(arg)
  return false unless arg.is_a?(Hash)
  return false unless arg.keys.sort.eql?(contract_hash.keys.sort)

  contract_hash.all? do |key, contract|
    contract_hash.key?(key) && Contract.valid?(arg[key], contract)
  end
end