Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty file size in Ruby?

Tags:

I'm trying to make a method that converts an integer that represents bytes to a string with a 'prettied up' format.

Here's my half-working attempt:

class Integer
  def to_filesize
    {
      'B'  => 1024,
      'KB' => 1024 * 1024,
      'MB' => 1024 * 1024 * 1024,
      'GB' => 1024 * 1024 * 1024 * 1024,
      'TB' => 1024 * 1024 * 1024 * 1024 * 1024
    }.each_pair { |e, s| return "#{s / self}#{e}" if self < s }
  end
end

What am I doing wrong?

like image 338
TeamBlast Avatar asked Apr 15 '13 23:04

TeamBlast


2 Answers

If you use it with Rails - what about standard Rails number helper?

http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human_size

number_to_human_size(number, options = {})

?

like image 159
Wile E. Avatar answered Dec 23 '22 11:12

Wile E.


How about the Filesize gem ? It seems to be able to convert from bytes (and other formats) into pretty printed values:

example:

Filesize.from("12502343 B").pretty      # => "11.92 MiB"

http://rubygems.org/gems/filesize

like image 44
David P Avatar answered Dec 23 '22 13:12

David P