Class: Contracts::Builtin::StrictHash

Inherits:
CallableClass show all
Defined in:
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.



426
427
428
429
# File 'lib/contracts/builtin_contracts.rb', line 426

def initialize(contract_hash)
  super()
  @contract_hash = contract_hash
end

Instance Attribute Details

#contract_hashObject (readonly)

Returns the value of attribute contract_hash.



424
425
426
# File 'lib/contracts/builtin_contracts.rb', line 424

def contract_hash
  @contract_hash
end

Instance Method Details

#valid?(arg) ⇒ Boolean

Returns:

  • (Boolean)


431
432
433
434
435
436
437
438
# File 'lib/contracts/builtin_contracts.rb', line 431

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