Module: AppInfo::Helper::HumanFileSize

Included in:
Android, Apple, DSYM::MachO, AppInfo::HarmonyOS, PE
Defined in:
lib/app_info/helper/file_size.rb

Constant Summary collapse

FILE_SIZE_UNITS =
%w[B KB MB GB TB].freeze

Instance Method Summary collapse

Instance Method Details

#file_to_human_size(file, human_size:) ⇒ Object



5
6
7
8
# File 'lib/app_info/helper/file_size.rb', line 5

def file_to_human_size(file, human_size:)
  number = ::File.size(file)
  human_size ? number_to_human_size(number) : number
end

#number_to_human_size(number) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/app_info/helper/file_size.rb', line 12

def number_to_human_size(number)
  if number.to_i < 1024
    exponent = 0
  else
    max_exp = FILE_SIZE_UNITS.size - 1
    exponent = (Math.log(number) / Math.log(1024)).to_i
    exponent = max_exp if exponent > max_exp
    number = Kernel.format('%<number>.2f', number: (number / (1024**exponent.to_f)))
  end

  "#{number} #{FILE_SIZE_UNITS[exponent]}"
end