Module: Tms::Space

Defined in:
lib/tms/space.rb

Constant Summary collapse

SIZE_SYMBOLS =
%w[B K M G T P E Z Y].freeze
COLORS =
[].tap do |colors|
  [:white, :black, :yellow, :red].each do |color|
    colors << {:foreground => color}
    colors << {:foreground => color, :extra => :bold}
  end
  colors << {:foreground => :yellow, :extra => :reversed}
  colors << {:foreground => :red, :extra => :reversed}
end.freeze
PRECISION =
1
LENGTH =
4 + PRECISION + 1
COEF =
1 / Math.log(10)
EMPTY_SPACE =
' ' * LENGTH
NOT_COUNTED_SPACE =
'!' * LENGTH

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.base10=(value) ⇒ Object (writeonly)

Sets the attribute base10

Parameters:

  • value

    the value to set the attribute base10 to.



24
25
26
# File 'lib/tms/space.rb', line 24

def base10=(value)
  @base10 = value
end

Class Method Details

.denominatorObject



25
26
27
# File 'lib/tms/space.rb', line 25

def denominator
  @denominator ||= @base10 ? 1000.0 : 1024.0
end

.space(size, options = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/tms/space.rb', line 29

def space(size, options = {})
  case size
  when false
    NOT_COUNTED_SPACE.bold.red
  when 0, nil
    EMPTY_SPACE
  else
    number, degree = size, 0
    while number.abs >= 1000 && degree < SIZE_SYMBOLS.length - 1
      number /= denominator
      degree += 1
    end

    space = "#{degree == 0 ? number.to_s : "%.#{PRECISION}f" % number}#{SIZE_SYMBOLS[degree]}".rjust(LENGTH)
    if options[:color]
      color = [[Math.log(size) * COEF, 1].max.to_i, COLORS.length].min - 1
      space = Colored.colorize(space, COLORS[color])
    end
    space
  end
end