class Toys::Acceptor::Pattern
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.
Public Class Methods
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.
@param regex [Regexp] Regular expression defining value values. @param converter [Proc] An optional converter function. May also be
given as a block. Note that the converter will be passed all elements of the `MatchData`.
@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] A converter function, if not provided as a normal
parameter.
Toys::Acceptor::Base::new
# File lib/toys/acceptor.rb, line 229 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
Public Instance Methods
Overrides {Toys::Acceptor::Base#convert} to use the given converter. @private
# File lib/toys/acceptor.rb, line 247 def convert(str, *extra) @converter ? @converter.call(str, *extra) : str end
Overrides {Toys::Acceptor::Base#match} to use the given regex. @private
# File lib/toys/acceptor.rb, line 239 def match(str) str.nil? ? [nil] : @regex.match(str) end