[EMAIL PROTECTED] wrote:
> Does anyone know if the reverse of the rails 20.kilobytes (megabytes/
> gigabytes etc.) exists? I have lots of values in my model that are
> stored as bytes and I'd like to easily convert them to a MB or GB
> approximation (say 1 decimal place) with *B as a suffix after the
> number.
This reply is over a year old, but I thought I'd archive the information
in this thread.
While ActionView in rails does have a helper for this, it requires you
to supply the number of decimal places. What follows is my own code (as
a Ramaze helper) that (by default) automatically determines the number
of decimal places based on the size of the answer.
For example:
[ 1500 12_000 130_000 1_400_000 ].each do |bytes|
puts nice_bytes( b )
end
#=> 1.46kB
#=> 11.7kB
#=> 127kB
#=> 1.34MB
module Ramaze::Helper::NiceBytes
K = 2.0**10
M = 2.0**20
G = 2.0**30
T = 2.0**40
def nice_bytes( bytes, max_digits=3 )
value, suffix, precision = case bytes
when 0...K
[ bytes, 'b', 0 ]
else
value, suffix = case bytes
when K...M : [ bytes / K, 'kB' ]
when M...G : [ bytes / M, 'MB' ]
when G...T : [ bytes / G, 'GB' ]
else [ bytes / T, 'TB' ]
end
used_digits = case value
when 0...10 : 1
when 10...100 : 2
when 100...1000 : 3
end
leftover_digits = max_digits - used_digits
[ value, suffix, leftover_digits > 0 ? leftover_digits : 0 ]
end
"%.#{precision}f#{suffix}" % value
end
end
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---