#
# Format filesize.
#
def Format.filesize(bytes, label_style = 0)
size = bytes
suffix = 'Bytes'
labels = {
0 => ['KB', 'MB'],
1 => ['Kilobytes', 'Megabytes'],
2 => ['KiB', 'MiB']
}
sizes = [1024, 1048576, 1073741824]
# KiB
if size >= 1024
size = (size / 1024).round
suffix = labels[label_style][0]
end
# MiB
if size >= 1024
size = (size / 1024).round
suffix = labels[label_style][1]
end
size.to_s + ' ' + suffix
end
Refactorings
No refactoring yet !
danielharan
September 22, 2008, September 22, 2008 16:18, permalink
Check out 'Show source' on http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#M001669
Tj Holowaychuk
September 22, 2008, September 22, 2008 21:55, permalink
For anyone interesting I ended up going with the following.
#
# Format filesize.
#
def Format.filesize(bytes, precision = 1)
bytes = bytes.to_f
case
when bytes < 1.kb; "%d #{Format.plural(bytes, 'byte', 'bytes')}" % bytes
when bytes < 1.mb; "%.#{precision}f #{Format.plural((bytes / 1.kb), 'kilobyte', 'kilobytes')}" % (bytes / 1.kb)
when bytes < 1.gb; "%.#{precision}f #{Format.plural((bytes / 1.mb), 'megabyte', 'megabytes')}" % (bytes / 1.mb)
when bytes >= 1.gb; "%.#{precision}f #{Format.plural((bytes / 1.gb), 'gigabyte', 'gigabytes')}" % (bytes / 1.gb)
end
end
#
# Format plural
#
def Format.plural(count, singular, plural)
count == 1 ? singular : plural
end
John
October 3, 2008, October 03, 2008 03:55, permalink
class Format
FILESIZE_UNITS = %w[ bytes kilobytes megabytes gigabytes ]
def self.filesize(bytes, precision = 1)
new(bytes).to_s(precision)
end
def initialize(bytes)
@bytes = bytes.to_f
end
def units
FILESIZE_UNITS.inject("bytes") do |method,current|
1.send(current) <= @bytes ? current : method
end
end
def humanized_units
bytes == 1 ? units.to_s.sub(/s$/, '') : units.to_s
end
def bytes
@bytes / 1.send(units)
end
def to_s(precision = 1)
precision = 0 if units == "bytes"
"%.#{precision}f %s" % [ bytes, humanized_units ]
end
end
class Numeric
def bytes
self
end
alias_method :byte, :bytes
alias_method :b, :bytes
def kilobytes
self * 1024
end
alias_method :kilobyte, :kilobytes
alias_method :kb, :kilobytes
def megabytes
self * 1024.kilobytes
end
alias_method :megabyte, :megabytes
alias_method :mb, :megabytes
def gigabytes
self * 1024.megabytes
end
alias_method :gigabyte, :gigabytes
alias_method :gb, :gigabytes
end
Ruby-newb coming through. I only really need to format sizes in bytes, KiB, and MiB, however I suppose a larger scale does not hurt! but im sure this one can be refactored quite alot