Class: CommandMapper::Types::Num

Inherits:
Type
  • Object
show all
Defined in:
lib/command_mapper/types/num.rb

Overview

Represents a numeric value.

Direct Known Subclasses

Hex

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(range: nil) ⇒ Num

Initializes the numeric value.

Parameters:

  • range (Range) (defaults to: nil)

    Specifies the range of acceptable numbers.



23
24
25
# File 'lib/command_mapper/types/num.rb', line 23

def initialize(range: nil)
  @range = range
end

Instance Attribute Details

#rangeRange? (readonly)

The optional range of acceptable numbers.

Returns:

  • (Range, nil)


15
16
17
# File 'lib/command_mapper/types/num.rb', line 15

def range
  @range
end

Instance Method Details

#format(value) ⇒ String

Formats a numeric value.

Parameters:

  • value (String, Integer, #to_i)

    The given value to format.

Returns:

  • (String)

    The formatted numeric value.



73
74
75
76
77
78
# File 'lib/command_mapper/types/num.rb', line 73

def format(value)
  case value
  when Integer, String then value.to_s
  else                      value.to_i.to_s
  end
end

#validate(value) ⇒ true, (false, String)

Validates a value.

Parameters:

  • value (String, Integer)

    The given value to validate.

Returns:

  • (true, (false, String))

    Returns true if the value is valid, or false and a validation error message if the value is not compatible.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/command_mapper/types/num.rb', line 39

def validate(value)
  case value
  when Integer
    # no-op
  when String
    unless value =~ /\A\d+\z/
      return [false, "contains non-numeric characters (#{value.inspect})"]
    end
  else
    unless value.respond_to?(:to_i)
      return [false, "cannot be converted into an Integer (#{value.inspect})"]
    end
  end

  if @range
    unless @range.include?(value.to_i)
      return [false, "(#{value.inspect}) not within the range of acceptable values (#{range.inspect})"]
    end
  end

  return true
end