Module: AppInfo::Util

Defined in:
lib/app_info/util.rb

Overview

AppInfo Util

Constant Summary collapse

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

Class Method Summary collapse

Class Method Details

.file_size(file, humanable) ⇒ Object



19
20
21
22
# File 'lib/app_info/util.rb', line 19

def self.file_size(file, humanable)
  file_size = File.size(file)
  humanable ? size_to_humanable(file_size) : file_size
end

.format_key(key) ⇒ Object



12
13
14
15
16
17
# File 'lib/app_info/util.rb', line 12

def self.format_key(key)
  key = key.to_s
  return key unless key.include?('_')

  key.split('_').map(&:capitalize).join('')
end

.size_to_humanable(number) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/app_info/util.rb', line 24

def self.size_to_humanable(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 = format('%<number>.2f', number: (number / (1024**exponent.to_f)))
  end

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

.unarchive(file, path: nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/app_info/util.rb', line 40

def self.unarchive(file, path: nil)
  path = path ? "#{path}-" : ''
  root_path = "#{Dir.mktmpdir}/AppInfo-#{path}#{SecureRandom.hex}"
  Zip::File.open(file) do |zip_file|
    if block_given?
      yield root_path, zip_file
    else
      zip_file.each do |f|
        f_path = File.join(root_path, f.name)
        FileUtils.mkdir_p(File.dirname(f_path))
        zip_file.extract(f, f_path) unless File.exist?(f_path)
      end
    end
  end

  root_path
end