Sha256: b5ebf1678ab322b6dcd81338ef34ae5974a01ee4b41af79e98253f2baef30481

Contents?: true

Size: 684 Bytes

Versions: 12

Compression:

Stored size: 684 Bytes

Contents

# frozen_string_literal: true

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

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

    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
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
app-info-3.3.0 lib/app_info/helper/file_size.rb
app-info-3.2.0 lib/app_info/helper/file_size.rb
app-info-3.2.0.beta1 lib/app_info/helper/file_size.rb
app-info-3.1.4 lib/app_info/helper/file_size.rb
app-info-3.1.3 lib/app_info/helper/file_size.rb
app-info-3.1.2 lib/app_info/helper/file_size.rb
app-info-3.1.1 lib/app_info/helper/file_size.rb
app-info-3.1.0 lib/app_info/helper/file_size.rb
app-info-3.0.0 lib/app_info/helper/file_size.rb
app-info-3.0.0.beta4 lib/app_info/helper/file_size.rb
app-info-3.0.0.beta3 lib/app_info/helper/file_size.rb
app-info-3.0.0.beta2 lib/app_info/helper/file_size.rb