Class: CommandMapper::Types::Hex

Inherits:
Num
  • Object
show all
Defined in:
lib/command_mapper/types/hex.rb

Overview

Represents a hexadecimal value.

Instance Attribute Summary

Attributes inherited from Num

#range

Instance Method Summary collapse

Constructor Details

#initialize(leading_zero: false, **kwargs) ⇒ Hex

Initializes the hex value.

Parameters:

  • leading_zero (Boolean) (defaults to: false)

    Specifies whether the hex value will start with 0x or not.

  • kwargs (Hash{Symbol => Object})

    Additional keyword arguments for Num#initialize.



19
20
21
22
23
# File 'lib/command_mapper/types/hex.rb', line 19

def initialize(leading_zero: false, **kwargs)
  super(**kwargs)

  @leading_zero = leading_zero
end

Instance Method Details

#format(value) ⇒ String

Formats the value.

Parameters:

  • value (#to_i)

    The given numeric value.

Returns:

  • (String)

    The formatted numeric value.



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/command_mapper/types/hex.rb', line 78

def format(value)
  case value
  when String
    if leading_zero? && !value.start_with?('0x')
      value = "0x#{value}"
    elsif (!leading_zero? && value.start_with?('0x'))
      value = value[2..]
    end

    value
  else
    value = value.to_i

    if leading_zero?
      "0x%x" % value
    else
      "%x" % value
    end
  end
end

#leading_zero?Boolean

Indicates whether the hex value will start with 0x or not.

Returns:

  • (Boolean)


32
33
34
# File 'lib/command_mapper/types/hex.rb', line 32

def leading_zero?
  @leading_zero
end

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

Validates a value.

Parameters:

  • value (String, Integer, Object)

    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.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/command_mapper/types/hex.rb', line 48

def validate(value)
  case value
  when String
    unless value =~ /\A(?:0x)?[A-Fa-f0-9]+\z/
      return [false, "not in hex format (#{value.inspect})"]
    end

    if @range
      unless @range.include?(value.to_i(16))
        return [false, "unacceptable value (#{value.inspect})"]
      end
    end

    return true
  else
    super(value)
  end
end