From ae87b48bef63314eecea32c7f402c48549cf087a Mon Sep 17 00:00:00 2001 From: Kyle Drake Date: Wed, 6 May 2015 18:12:24 -0700 Subject: [PATCH] fix pretty bytes (i hope) --- ext/numeric.rb | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/ext/numeric.rb b/ext/numeric.rb index 5a0d7064..3f385fa2 100644 --- a/ext/numeric.rb +++ b/ext/numeric.rb @@ -10,15 +10,24 @@ class Numeric end def to_bytes_pretty - space = (self.to_f / ONE_MEGABYTE).round(2) - space = space.to_i if space.denominator == 1 -# if space >= 1000000 -# "#{space/1000000} TB" - if space >= 1000 - "#{(space/1000).to_comma_separated} GB" - else - "#{space.to_comma_separated} MB" - end + computed = nil + unit = nil + { + 'B' => 1000, + 'KB' => 1000 * 1000, + 'MB' => 1000 * 1000 * 1000, + 'GB' => 1000 * 1000 * 1000 * 1000, + 'TB' => 1000 * 1000 * 1000 * 1000 * 1000 + }.each_pair { |e, s| + if self < s + computed = (self.to_f / (s / 1000)).round(2) + unit = e + break + end + } + computed = computed.to_i if computed.modulo(1) == 0.0 + + "#{computed} #{unit}" end def to_comma_separated