class Contracts::Builtin::Optional

Use this for specifying optional keyword argument Example: Optional[Num]

Constants

UNABLE_TO_USE_OUTSIDE_OF_OPT_HASH

Attributes

contract[R]
within_opt_hash[R]

Public Class Methods

_valid?(hash, key, contract) click to toggle source
# File lib/contracts/builtin_contracts.rb, line 502
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
new(contract) click to toggle source
Calls superclass method
# File lib/contracts/builtin_contracts.rb, line 509
def initialize(contract)
  super()
  @contract = contract
  @within_opt_hash = false
end

Public Instance Methods

inspect() click to toggle source
# File lib/contracts/builtin_contracts.rb, line 529
def inspect
  to_s
end
to_s() click to toggle source
# File lib/contracts/builtin_contracts.rb, line 525
def to_s
  "Optional[#{formatted_contract}]"
end
valid?(value) click to toggle source
# File lib/contracts/builtin_contracts.rb, line 520
def valid?(value)
  ensure_within_opt_hash
  Contract.valid?(value, contract)
end
within_opt_hash!() click to toggle source
# File lib/contracts/builtin_contracts.rb, line 515
def within_opt_hash!
  @within_opt_hash = true
  self
end

Private Instance Methods

ensure_within_opt_hash() click to toggle source
# File lib/contracts/builtin_contracts.rb, line 537
def ensure_within_opt_hash
  return if within_opt_hash

  fail ArgumentError, UNABLE_TO_USE_OUTSIDE_OF_OPT_HASH
end
formatted_contract() click to toggle source
# File lib/contracts/builtin_contracts.rb, line 543
def formatted_contract
  Formatters::InspectWrapper.create(contract)
end