Sha256: ddea55a1e22fbdf7e5ebd5e720673360c1d17a2f4f86d6c079f8f3c3ca69e574

Contents?: true

Size: 1.32 KB

Versions: 2

Compression:

Stored size: 1.32 KB

Contents

require_relative 'human_size/version'
require_relative 'human_size/overloads'

#
# Add docs
#
module HumanSize
    #
    # Add docs
    #
    class Size
        def self.human_size(bytes, a_kilobyte_is_1024_bytes = true)
            suffixes_table = {
                # Unit prefixes used for SI file sizes.
                'SI' => ['B', 'KB', 'MB', 'GB', 'TB', 'Pb', 'EB', 'ZB', 'YB'],
                # Unit prefixes used for binary file sizes.
                'BINARY' => ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'Pib', 'EiB', 'ZiB', 'YiB']
            }

            return 'unknown' if bytes < 0
            return '0.0 B' if bytes.zero?

            units = if a_kilobyte_is_1024_bytes
                        suffixes_table['BINARY']
                    else
                        suffixes_table['SI']
                    end

            multiple = if a_kilobyte_is_1024_bytes
                           1024
                       else
                           1000
                       end

            exp = (Math.log(bytes) / Math.log(multiple)).to_i
            exp = units.length if exp > units.length

            # rubocop:disable Layout/SpaceAroundOperators
            format('%<bytes>.1f %<unit>s', bytes: bytes.to_f / multiple ** exp, unit: units[exp])
            # rubocop:enable Layout/SpaceAroundOperators
        end
    end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
human_size-1.1.1 lib/human_size.rb
human_size-1.1.0 lib/human_size.rb