Module: ImageOptim::Space

Defined in:
lib/image_optim/space.rb

Overview

Present size in readable form as fixed length string

Constant Summary collapse

SIZE_SYMBOLS =
%w[B K M G T P E].freeze
BASE =
1024.0
PRECISION =
1
LENGTH =
PRECISION + 4 + 1
EMPTY_SPACE =
' ' * LENGTH

Class Method Summary collapse

Class Method Details

.space(size) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/image_optim/space.rb', line 13

def self.space(size)
  case size
  when 0, nil
    EMPTY_SPACE
  else
    log_denominator = Math.log(size.abs) / Math.log(BASE)
    degree = [log_denominator.floor, SIZE_SYMBOLS.length - 1].min
    number_string = if degree == 0
      size.to_s
    else
      denominator = BASE**degree
      number = size / denominator
      format("%.#{PRECISION}f", number)
    end
    "#{number_string}#{SIZE_SYMBOLS[degree]}".rjust(LENGTH)
  end
end