Class: File
Class Method Summary collapse
-
.human_size(size) ⇒ String
Gives the size of a file as a string including the unit.
Instance Method Summary collapse
-
#human_size ⇒ String
Returns the human readable form of the file’s size.
Class Method Details
.human_size(size) ⇒ String
Gives the size of a file as a string including the unit. It will choose the unit to use based on how big the file is. Decimals will be rounded to the tenths. size
is either a Numeric containing the size in bytes, a File object, or a String with the name of the file.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/nutella/core_ext/file.rb', line 20 def self.human_size(size) bytes = size.is_a?(Numeric) ? size : File.size(size) rescue nil return "Empty" if bytes.blank? || bytes.zero? return "1 Byte" if bytes == 1 divisor, unit = if bytes < Numeric::KILOBYTE [1, "Bytes"] elsif bytes < Numeric::MEGABYTE [Numeric::KILOBYTE, "KB"] elsif bytes < Numeric::GIGABYTE [Numeric::MEGABYTE, "MB"] else [Numeric::GIGABYTE, "GB"] end "%g #{unit}" % (bytes.to_f / divisor).round(1) end |
Instance Method Details
#human_size ⇒ String
Returns the human readable form of the file’s size.
48 49 50 |
# File 'lib/nutella/core_ext/file.rb', line 48 def human_size File.human_size self end |