Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friendly Byte Formatting in Rails

I need to format an integer representation of bytes into something friendly, and I'm hoping that there's a utility function in Ruby or in Rails that will do that formatting for me (to perpetuate my laziness, of course.)

I'm looking for something that would look like:

format_bytes(1024)     -> "1 KB"
format_bytes(1048576)  -> "1 MB"

Looks like there's some stuff in ActiveSupport to do it the other way around, but I haven't found a way to do it in this direction.

If there isn't one that exists, does anyone have a particularly elegant solution?

like image 725
Jim Fiorato Avatar asked Dec 08 '08 16:12

Jim Fiorato


3 Answers

Number to human size is what you're looking for.

require 'action_view'
include ActionView::Helpers::NumberHelper
number_to_human_size(123)                                          # => 123 Bytes
number_to_human_size(1234)                                         # => 1.2 KB
number_to_human_size(12345)                                        # => 12.1 KB
number_to_human_size(1234567)                                      # => 1.2 MB
number_to_human_size(1234567890)                                   # => 1.1 GB
number_to_human_size(1234567890123)                                # => 1.1 TB
number_to_human_size(1234567, :precision => 2)                     # => 1.18 MB
number_to_human_size(483989, :precision => 0)                      # => 473 KB
number_to_human_size(1234567, :precision => 2, :separator => ',')  # => 1,18 MB
like image 58
mwilliams Avatar answered Sep 25 '22 20:09

mwilliams


Accepted answer still work, but requires actionpack instead of actionview in newer rails.

require 'actionpack'
like image 42
Tim Peters Avatar answered Sep 24 '22 20:09

Tim Peters


Accepted answer it's perfect, but I didn't need the first two lines. I only put:

number_to_human_size(123)                                          # => 123 Bytes
number_to_human_size(1234)                                         # => 1.2 KB
number_to_human_size(12345)                                        # => 12.1 KB
number_to_human_size(1234567)                                      # => 1.2 MB
number_to_human_size(1234567890)                                   # => 1.1 GB
number_to_human_size(1234567890123)                                # => 1.1 TB
number_to_human_size(1234567, :precision => 2)                     # => 1.18 MB
number_to_human_size(483989, :precision => 0)                      # => 473 KB
number_to_human_size(1234567, :precision => 2, :separator => ',')  # => 1,18 MB

and works like a charm.

like image 20
facundofarias Avatar answered Sep 22 '22 20:09

facundofarias