class ValidateSuffixedNumber
Class to parse and validate suffixed numbers.
Constants
- ABBREVIATIONS_RE
- FLOAT_RE
- INTEGER_RE
- MAGNIFIERS_RE
- SCIENTIFIC_RE
- SI_ABBREVIATIONS
- SI_MAGNIFIERS
- SI_MULTIPLIERS
methods for validating strings as optionally suffixed numbers (floats or integers)
- VERSION
Public Class Methods
parse_integer(string_arg)
click to toggle source
# File lib/validate_suffixed_number.rb, line 35 def parse_integer(string_arg) parse_number(string_arg)&.to_i end
parse_integer_option(key, options, error_msg = nil)
click to toggle source
# File lib/validate_suffixed_number.rb, line 31 def parse_integer_option(key, options, error_msg = nil) parse_value_option(key, options, :parse_integer, error_msg) end
parse_number(string_arg)
click to toggle source
# File lib/validate_suffixed_number.rb, line 39 def parse_number(string_arg) str = string_arg&.strip if SCIENTIFIC_RE.match?(str) # scientific notation? str.to_f elsif (mdata = MAGNIFIERS_RE.match(str)) # eg: 1.2 billion, 12 trillion, 1500 thousand, 15000 suffix = mdata[2].downcase.to_sym mdata[1].sub(' ', '').to_f * SI_MULTIPLIERS[suffix] elsif (mdata = ABBREVIATIONS_RE.match(str)) # eg: 1.2G, 12T, 1500K, 15000 suffix = mdata[2].upcase.to_sym mdata[1].gsub(' ', '').to_f * SI_MULTIPLIERS[suffix] elsif FLOAT_RE.match?(str) str.sub(' ', '').to_f elsif INTEGER_RE.match?(str) str.sub(' ', '').to_i end end
parse_numeric_option(key, options, error_msg = nil)
click to toggle source
# File lib/validate_suffixed_number.rb, line 27 def parse_numeric_option(key, options, error_msg = nil) parse_value_option(key, options, :parse_number, error_msg) end
Private Class Methods
error(msg)
click to toggle source
# File lib/validate_suffixed_number.rb, line 76 def error(msg) raise ArgumentError, msg end
error_message(msg, arg)
click to toggle source
# File lib/validate_suffixed_number.rb, line 68 def error_message(msg, arg) if msg.include?('%s') error sprintf(msg, arg) else error "#{msg}: '#{arg}'" end end
parse_value_option(key, options, validator, error_msg = nil)
click to toggle source
# File lib/validate_suffixed_number.rb, line 60 def parse_value_option(key, options, validator, error_msg = nil) options ||= {} arg = options[key]&.strip error("No value given for --#{key}") if arg.nil? (options[key] = send(validator, arg)) || error_message(error_msg || "Bad value for --#{key}: '%s'", arg) end