Class: Contracts::Builtin::Optional

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 for specifying optional keyword argument Example: Optional[Num]

Constant Summary collapse

UNABLE_TO_USE_OUTSIDE_OF_OPT_HASH =
"Unable to use Optional contract outside of KeywordArgs contract"

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from CallableClass

[]

Constructor Details

#initialize(contract) ⇒ Optional

Returns a new instance of Optional.



480
481
482
483
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 480

def initialize(contract)
  @contract = contract
  @within_opt_hash = false
end

Class Method Details

._valid?(hash, key, contract) ⇒ Boolean

Returns:

  • (Boolean)


474
475
476
477
478
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 474

def self._valid?(hash, key, contract)
  return Contract.valid?(hash[key], contract) unless contract.is_a?(Optional)
  contract.within_opt_hash!
  !hash.key?(key) || Contract.valid?(hash[key], contract)
end

Instance Method Details

#inspectObject



499
500
501
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 499

def inspect
  to_s
end

#to_sObject



495
496
497
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 495

def to_s
  "Optional[#{formatted_contract}]"
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


490
491
492
493
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 490

def valid?(value)
  ensure_within_opt_hash
  Contract.valid?(value, contract)
end

#within_opt_hash!Object



485
486
487
488
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 485

def within_opt_hash!
  @within_opt_hash = true
  self
end