class Toys::Acceptor::Simple

An acceptor that uses a simple function to validate and convert input. The function must take the input string as its argument, and either return the converted object to indicate success, or raise an exception or return the sentinel {Toys::Acceptor::REJECT} to indicate invalid input.

Public Class Methods

new(function = nil, type_desc: nil, well_known_spec: nil, &block) click to toggle source

Create a simple acceptor.

You should provide an acceptor function, either as a proc in the `function` argument, or as a block. The function must take as its one argument the input string. If the string is valid, the function must return the value to store in the tool's data. If the string is invalid, the function may either raise an exception (which must descend from `StandardError`) or return {Toys::Acceptor::REJECT}.

@param function [Proc] The acceptor function @param type_desc [String] Type description string, shown in help.

Defaults to {Toys::Acceptor::DEFAULT_TYPE_DESC}.

@param well_known_spec [Object] The well-known acceptor spec associated

with this acceptor, or `nil` for none.

@param block [Proc] The acceptor function, if not provided as a normal

parameter.
Calls superclass method Toys::Acceptor::Base::new
# File lib/toys/acceptor.rb, line 174
def initialize(function = nil, type_desc: nil, well_known_spec: nil, &block)
  super(type_desc: type_desc, well_known_spec: well_known_spec)
  @function = function || block || proc { |s| s }
end

Public Instance Methods

convert(_str, result) click to toggle source

Overrides {Toys::Acceptor::Base#convert} to use the given function's result. @private

# File lib/toys/acceptor.rb, line 193
def convert(_str, result)
  result
end
match(str) click to toggle source

Overrides {Toys::Acceptor::Base#match} to use the given function. @private

# File lib/toys/acceptor.rb, line 183
def match(str)
  result = @function.call(str) rescue REJECT # rubocop:disable Style/RescueModifier
  result.equal?(REJECT) ? nil : [str, result]
end