Class: Toys::Acceptor::Range

Inherits:
Simple show all
Defined in:
lib/toys/acceptor.rb

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 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.

Instance Attribute Summary collapse

Attributes inherited from Base

#type_desc, #well_known_spec

Instance Method Summary collapse

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.

Parameters:

  • range (Range)

    The range of acceptable values

  • converter (Proc) (defaults to: nil)

    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.

  • 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)

    Converter function, if not provided as a normal parameter.



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

#rangeRange (readonly)

The range being checked.

Returns:



376
377
378
# File 'lib/toys/acceptor.rb', line 376

def range
  @range
end