module Tins::Unit

Constants

PREFIX_F
PREFIX_LC
PREFIX_UC
Prefix

Public Instance Methods

format(value, format: '%f %U', prefix: 1024, unit: ?b) click to toggle source
# File lib/tins/unit.rb, line 36
def format(value, format: '%f %U', prefix: 1024, unit: ?b)
  prefixes = prefixes(prefix)
  first_prefix = prefixes.first or
    raise ArgumentError, 'a non-empty array of prefixes is required'
  if value.zero?
    result = format.sub('%U', unit)
    result %= value
  else
    prefix = prefixes[
      (first_prefix.fraction ? -1 : 1) * Math.log(value.abs) / Math.log(first_prefix.step)
    ]
    result = format.sub('%U', "#{prefix.name}#{unit}")
    result %= (value / prefix.multiplier.to_f)
  end
end
parse(string, format: '%f %U', unit: ?b, prefix: nil) click to toggle source

Parse the string string if it matches format with the unit unit and the prefixes specified by prefix.

# File lib/tins/unit.rb, line 169
def parse(string, format: '%f %U', unit: ?b, prefix: nil)
  prefixes = prefixes(prefix)
  FormatParser.new(format, UnitParser.new(string, unit, prefixes)).parse
end
parse?(string, **options) click to toggle source
# File lib/tins/unit.rb, line 174
def parse?(string, **options)
  parse(string, **options)
rescue ParserError
  nil
end
prefixes(identifier) click to toggle source
# File lib/tins/unit.rb, line 23
def prefixes(identifier)
  case identifier
  when :uppercase, :uc, 1024
    PREFIX_UC
  when :lowercase, :lc, 1000
    PREFIX_LC
  when :fraction, :f, 0.001
    PREFIX_F
  when Array
    identifier
  end
end