Sha256: 78ca151d2a6f13af1e133bac2c43fb2ac8167d24559507b0a1130af6290a27fb
Contents?: true
Size: 1.9 KB
Versions: 2
Compression:
Stored size: 1.9 KB
Contents
require 'command_mapper/types/num' module CommandMapper module Types # # Represents a hexadecimal value. # class Hex < Num # # Initializes the hex value. # # @param [Boolean] leading_zero # Specifies whether the hex value will start with `0x` or not. # # @param [Hash{Symbol => Object}] kwargs # Additional keyword arguments for {Type#initialize}. # def initialize(leading_zero: false) @leading_zero = leading_zero end # # Indicates whether the hex value will start with `0x` or not. # # @return [Boolean] # def leading_zero? @leading_zero end # # Validates a value. # # @param [String, Integer, Object] value # The given value to validate. # # @return [true, (false, String)] # Returns true if the value is valid, or `false` and a validation error # message if the value is not compatible. # 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 return true else super(value) end end # # Formats the value. # # @param [#to_i] value # The given numeric value. # # @return [String] # The formatted numeric value. # 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 end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
command_mapper-0.1.2 | lib/command_mapper/types/hex.rb |
command_mapper-0.1.1 | lib/command_mapper/types/hex.rb |