Forum: Ruby on Rails Human readable byte size

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ae1e2c5ed00dc3169c99c48c7e329dac?d=identicon&s=25 Ry Dahl (Guest)
on 2006-12-22 18:28
(Received via mailing list)
Hi
I wasn't able to find this function in Rails. Probably it already
exists somewhere- if not, maybe this will save someone 2 minutes

 def human_size(size)
  if size < 1.kilobyte
    size + " Bytes"
  elsif size < 1.megabyte
    sprintf("%.0f KB", size / 1.kilobyte.to_f)
  elsif size < 1.gigabyte
    sprintf("%.1f MB", size / 1.megabyte.to_f)
  elsif size < 1.terabyte
    sprintf("%.1f GB", size / 1.gigabyte.to_f)
  elsif size < 1.petabyte
    sprintf("%.1f TB", size / 1.terabyte.to_f)
  elsif size < 1.exabyte
    sprintf("%.1f PB", size / 1.petabyte.to_f)
  else
    sprintf("%.1f EB", size / 1.exabyte.to_f)
  end
 end

Ryan
00db1b82429b648c68823e79e9bfc833?d=identicon&s=25 Thomas, Mark - BLS CTR (Guest)
on 2006-12-22 21:38
(Received via mailing list)
> I wasn't able to find this function in Rails. Probably it
> already exists somewhere- if not, maybe this will save
> someone 2 minutes

It's in ActionView::Helpers::NumberHelper.

It's even called human_size via an alias. If you had tried it in a view
before coding it, it would have worked! That has happened to me a couple
times. Rails rocks.

FYI: Here's the implementation. Doesn't go past TB.

# File vendor/rails/actionpack/lib/action_view/helpers/number_helper.rb,
line 87
def number_to_human_size(size)
  case
    when size < 1.kilobyte: '%d Bytes' % size
    when size < 1.megabyte: '%.1f KB'  % (size / 1.0.kilobyte)
    when size < 1.gigabyte: '%.1f MB'  % (size / 1.0.megabyte)
    when size < 1.terabyte: '%.1f GB'  % (size / 1.0.gigabyte)
    else                    '%.1f TB'  % (size / 1.0.terabyte)
  end.sub('.0', '')
rescue
  nil
end
2f9a03aa0fcfe945229cb6126eda2cb2?d=identicon&s=25 Philip Hallstrom (Guest)
on 2006-12-22 22:06
(Received via mailing list)
> Hi
> I wasn't able to find this function in Rails. Probably it already
> exists somewhere- if not, maybe this will save someone 2 minutes

It is...

number_to_human_size(size)

Returns a formatted-for-humans file size.

Examples:

   human_size(123)          => 123 Bytes
   human_size(1234)         => 1.2 KB
   human_size(12345)        => 12.1 KB
   human_size(1234567)      => 1.2 MB
   human_size(1234567890)   => 1.1 GB
This topic is locked and can not be replied to.