Sha256: ef0f8d5bab9a81bc46b93f4f67200ce10481c3816d2d04d34e526f5a96b11f83

Contents?: true

Size: 677 Bytes

Versions: 1

Compression:

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

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
app-info-3.0.0.beta1 lib/app_info/helper/file_size.rb