Class: StaticdUtils::FileSize

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

Overview

Class to convert file size in octect to human readable size.

Example:

Staticd::FileSize.new(1000).to_s
# => "1KB"

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ FileSize

Returns a new instance of FileSize.



10
11
12
# File 'lib/staticd_utils/file_size.rb', line 10

def initialize(size)
  @size = size
end

Instance Method Details

#to_sObject



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/staticd_utils/file_size.rb', line 14

def to_s
  units = %w(B KB MB GB TB)
  base = 1000
  return "#{@size}#{units[0]}" if @size < base

  exponent = (Math.log(@size) / Math.log(base)).to_i
  exponent = units.size - 1 if exponent > units.size - 1

  human_size = @size / base**exponent
  "#{human_size}#{units[exponent]}"
end