Class: Toys::Acceptor::Range
Overview
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 toInteger
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 toFloat
. - If the range beginning and end are both
Rational
, then input strings are likewise converted toRational
. - If the range beginning and end are both
Numeric
types but different subtypes (e.g. anInteger
and aFloat
), 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.
Instance Attribute Summary collapse
-
#range ⇒ Range
readonly
The range being checked.
Attributes inherited from Base
Instance Method Summary collapse
-
#initialize(range, converter = nil, type_desc: nil, well_known_spec: nil, &block) ⇒ Range
constructor
Create an acceptor.
Methods inherited from Base
#convert, #match, #suggestions, #to_s
Constructor Details
#initialize(range, converter = nil, type_desc: nil, well_known_spec: nil, &block) ⇒ Range
Create an acceptor.
363 364 365 366 367 368 369 370 |
# File 'lib/toys/acceptor.rb', line 363 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 |
Instance Attribute Details
#range ⇒ Range (readonly)
The range being checked.
376 377 378 |
# File 'lib/toys/acceptor.rb', line 376 def range @range end |