Class: SpeedFormat

Inherits:
Object
  • Object
show all
Defined in:
lib/speed_format.rb

Constant Summary collapse

@@units =
[nil, :k, :M, :G, :T, :P, :E]

Class Method Summary collapse

Class Method Details

.format(bps, unit = nil, bytes = nil) ⇒ Object

Get bps in unit and format it, if bytes is provided, the output is in bytes instead of bits



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/speed_format.rb', line 20

def self.format(bps, unit=nil, bytes=nil)
    if not @@units.include?(unit)
      raise ArgumentError, "Not a valid prefix"
    end
    bps = BigDecimal(bps.to_s).abs
    if bytes == :bytes
      bps /= 8
    end
    index = @@units.index(unit)
    d = bps % 1 != 0.0 ? 1 : -1 # If there's right side digits, should move the comma right, otherwise left
    if bps != 0.0
      if d == 1 # Move to the right (non-integers)
        while (bps % 1 != 0.0) and (index-d >= 0) and (index-d < @@units.length)
            bps *= 10.0**(d*3)
            index -= d
        end
      else # Move to the left
        next_v = (bps*10.0**(d*3)) # Calculating the next
        while (next_v % 1 == 0.0) and (index-d >= 0) and (index-d < @@units.length)
            bps *= 10.0**(d*3)
            index -= d
            next_v = bps*10.0**(d*3)
        end
      end
    else
      index = 0
    end
    bps = bps.to_s("F")
    return bps[-2,2] == ".0" ? bps[0..-3].to_i : Float(bps), @@units[index]
end

.format_string(*args) ⇒ Object



51
52
53
54
55
56
# File 'lib/speed_format.rb', line 51

def self.format_string(*args)
  out = self.format(*args)
  out[0] = out[0] % 1 == 0.0 ? out[0].to_i : out[0]
  suffix = args.include?(:bytes) ? "B/s" : "bit/s"
  out.join(" ") + suffix
end

.unitsObject



58
59
60
# File 'lib/speed_format.rb', line 58

def self.units
  @@units
end