class Toys::Acceptor::Range
An acceptor that recognizes a range of values.
The input argument is matched against the given range. For example, you can match against the integers from 1 to 10 by passing the range `(1..10)`.
You can also provide a conversion function that takes the input string and converts it an object that can be compared by the range. If you do not provide a converter, a default converter will be provided depending on the types of objects serving as the range limits. Specifically:
* If the range beginning and end are both `Integer`, then input strings are likewise converted to `Integer` when matched against the range. Accepted values are returned as integers. * If the range beginning and end are both `Float`, then input strings are likewise converted to `Float`. * If the range beginning and end are both `Rational`, then input strings are likewise converted to `Rational`. * If the range beginning and end are both `Numeric` types but different subtypes (e.g. an `Integer` and a `Float`), then any type of numeric input (integer, float, rational) is accepted and matched against the range. * If the range beginning and/or end are not numeric types, then no conversion is done by default.
Attributes
The range being checked. @return [Range]
Public Class Methods
Create an acceptor.
@param range [Range] The range of acceptable values @param converter [Proc] A converter proc that takes an input string and
attempts to convert it to a type comparable by the range. For numeric ranges, this can be omitted because one is provided by default. You should provide a converter for other types of ranges. You can also pass the converter as a block.
@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] Converter function, if not provided as a normal
parameter.
Toys::Acceptor::Simple::new
# File lib/toys/acceptor.rb, line 356 def initialize(range, converter = nil, type_desc: nil, well_known_spec: nil, &block) converter ||= block || make_converter(range.begin, range.end) super(type_desc: type_desc, well_known_spec: well_known_spec) do |val| val = converter.call(val) if converter val.nil? || range.include?(val) ? val : REJECT end @range = range end
Private Instance Methods
# File lib/toys/acceptor.rb, line 373 def make_converter(val1, val2) if val1.is_a?(::Integer) && val2.is_a?(::Integer) INTEGER_CONVERTER elsif val1.is_a?(::Float) && val2.is_a?(::Float) FLOAT_CONVERTER elsif val1.is_a?(::Rational) && val2.is_a?(::Rational) RATIONAL_CONVERTER elsif val1.is_a?(::Numeric) && val2.is_a?(::Numeric) NUMERIC_CONVERTER end end