Class: Toys::Acceptor::Pattern

Inherits:
Base
  • Object
show all
Defined in:
lib/toys/acceptor.rb

Overview

An acceptor that uses a regex to validate input. It also supports a custom conversion function that generates the final value from the match results.

Instance Attribute Summary

Attributes inherited from Base

#type_desc, #well_known_spec

Instance Method Summary collapse

Methods inherited from Base

#suggestions, #to_s

Constructor Details

#initialize(regex, converter = nil, type_desc: nil, well_known_spec: nil, &block) ⇒ Pattern

Create a pattern acceptor.

You must provide a regular expression (or any object that duck-types Regexp#match) as a validator.

You may also optionally provide a converter, either as a proc or a block. A converter must take as its arguments the values in the MatchData returned from a successful regex match. That is, the first argument is the original input string, and the remaining arguments are the captures. The converter must return the final converted value. If no converter is provided, no conversion is done and the input string is returned.

Parameters:

  • regex (Regexp)

    Regular expression defining value values.

  • converter (Proc) (defaults to: nil)

    An optional converter function. May also be given as a block. Note that the converter will be passed all elements of the MatchData.

  • type_desc (String) (defaults to: nil)

    Type description string, shown in help. Defaults to DEFAULT_TYPE_DESC.

  • well_known_spec (Object) (defaults to: nil)

    The well-known acceptor spec associated with this acceptor, or nil for none.

  • block (Proc)

    A converter function, if not provided as a normal parameter.



231
232
233
234
235
# File 'lib/toys/acceptor.rb', line 231

def initialize(regex, converter = nil, type_desc: nil, well_known_spec: nil, &block)
  super(type_desc: type_desc, well_known_spec: well_known_spec)
  @regex = regex
  @converter = converter || block
end