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 473
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
# File lib/contracts/builtin_contracts.rb, line 479
def initialize(contract)
  @contract = contract
  @within_opt_hash = false
end

Public Instance Methods

inspect() click to toggle source
# File lib/contracts/builtin_contracts.rb, line 498
def inspect
  to_s
end
to_s() click to toggle source
# File lib/contracts/builtin_contracts.rb, line 494
def to_s
  "Optional[#{formatted_contract}]"
end
valid?(value) click to toggle source
# File lib/contracts/builtin_contracts.rb, line 489
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 484
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 506
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 511
def formatted_contract
  Formatters::InspectWrapper.create(contract)
end