Class: Necromancer::RangeConverters::StringToRangeConverter

Inherits:
Converter
  • Object
show all
Defined in:
lib/necromancer/converters/range.rb

Overview

An object that converts a String to a Range

Instance Attribute Summary

Attributes inherited from Converter

#config, #convert, #source, #target

Instance Method Summary collapse

Methods inherited from Converter

create, #initialize, #raise_conversion_type

Constructor Details

This class inherits a constructor from Necromancer::Converter

Instance Method Details

#call(value, strict: config.strict) ⇒ Object

Convert value to Range type with possible ranges

Examples:

converter.call("0,9")  # => (0..9)
converter.call("0-9")  # => (0..9)

Parameters:

  • value (Object)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/necromancer/converters/range.rb', line 34

def call(value, strict: config.strict)
  if match = value.match(SINGLE_DIGIT_MATCHER)
    digit = cast_to_num(match[:digit])
    ::Range.new(digit, digit)
  elsif match = value.match(DIGIT_MATCHER)
    open = cast_to_num(match[:open])
    close = cast_to_num(match[:close])
    ::Range.new(open, close, match[:sep].gsub(/\s*/, "") == "...")
  elsif match = value.match(LETTER_MATCHER)
    ::Range.new(match[:open], match[:close],
                match[:sep].gsub(/\s*/, "") == "...")
  else
    strict ? raise_conversion_type(value) : value
  end
end

#cast_to_num(str) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Convert range end to numeric value



53
54
55
56
57
58
59
# File 'lib/necromancer/converters/range.rb', line 53

def cast_to_num(str)
  Integer(str)
rescue ArgumentError
  Float(str)
rescue ArgumentError
  nil
end