Class: CommandMapper::Types::Dec

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

Overview

Represents a decimal value (ex: 1.5).

Since:

  • 0.3.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(range: nil) ⇒ Dec

Initializes the decimal type.

Parameters:

  • range (Range<Float,Float>) (defaults to: nil)

    Specifies the range of acceptable numbers.

Since:

  • 0.3.0



25
26
27
# File 'lib/command_mapper/types/dec.rb', line 25

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

Instance Attribute Details

#rangeRange<Float,Float>? (readonly)

The optional range of acceptable decimal numbers.

Returns:

  • (Range<Float,Float>, nil)

Since:

  • 0.3.0



17
18
19
# File 'lib/command_mapper/types/dec.rb', line 17

def range
  @range
end

Instance Method Details

#format(value) ⇒ String

Formats a decimal value.

Parameters:

  • value (String, Float, #to_f)

    The given value to format.

Returns:

  • (String)

    The formatted decimal value.

Since:

  • 0.3.0



75
76
77
78
79
80
# File 'lib/command_mapper/types/dec.rb', line 75

def format(value)
  case value
  when Float, String then value.to_s
  else                    value.to_f.to_s
  end
end

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

Validates a value.

Parameters:

  • value (String, Numeric)

    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.

Since:

  • 0.3.0



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

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

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

  return true
end