class HumanSize::Size
Add docs
Public Class Methods
human_size(bytes, a_kilobyte_is_1024_bytes = true)
click to toggle source
# File lib/human_size.rb, line 14 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.negative? 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