Class: MetricNumber

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/rvc/util.rb

Constant Summary collapse

DECIMAL_PREFIXES =
{
  'k' => 10 ** 3,
  'M' => 10 ** 6,
  'G' => 10 ** 9,
  'T' => 10 ** 12,
  'P' => 10 ** 15,
}
BINARY_PREFIXES =
{
  'Ki' => 2 ** 10,
  'Mi' => 2 ** 20,
  'Gi' => 2 ** 30,
  'Ti' => 2 ** 40,
  'Pi' => 2 ** 50,
}
CANONICAL_PREFIXES =

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(val, unit, binary = false) ⇒ MetricNumber

Returns a new instance of MetricNumber.



345
346
347
348
349
# File 'lib/rvc/util.rb', line 345

def initialize val, unit, binary=false
  @unit = unit
  @binary = binary
  super val.to_f
end

Instance Attribute Details

#binaryObject (readonly)

Returns the value of attribute binary.



343
344
345
# File 'lib/rvc/util.rb', line 343

def binary
  @binary
end

#unitObject (readonly)

Returns the value of attribute unit.



343
344
345
# File 'lib/rvc/util.rb', line 343

def unit
  @unit
end

Class Method Details

.parse(str) ⇒ Object



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/rvc/util.rb', line 385

def self.parse str
  if str =~ /^([0-9,.]+)\s*([kmgtp]i?)?/i
    x = $1.delete(',').to_f
    binary = false
    if $2
      prefix = $2.downcase
      binary = prefix[1..1] == 'i'
      prefixes = binary ? BINARY_PREFIXES : DECIMAL_PREFIXES
      multiple = prefixes[CANONICAL_PREFIXES[prefix]]
    else
      multiple = 1
    end
    units = $'
    new x*multiple, units, binary
  else
    raise "Problem parsing SI number #{str.inspect}"
  end
end

Instance Method Details

#to_sObject



351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/rvc/util.rb', line 351

def to_s
  limit = @binary ? 1024 : 1000
  if self < limit
    prefix = ''
    multiple = 1
  else
    prefixes = @binary ? BINARY_PREFIXES : DECIMAL_PREFIXES
    prefixes = prefixes.sort_by { |k,v| v }
    prefix, multiple = prefixes.find { |k,v| self/v < limit }
    prefix, multiple = prefixes.last unless prefix
  end
  ("%0.2f %s%s" % [self/multiple, prefix, @unit]).strip
end