class Lolita::Support::Bytes

Convert bytes to closest possible unit.

Example

byte_converter=Lolita::FileUpload::Bytes.new(1024)
byte_converter.unit #=> kilobytes
byte_convertes.value #=> 1.0

Public Class Methods

new(bytes) click to toggle source
# File lib/support/bytes.rb, line 13
def initialize(bytes)
  @power=0
  @bytes=bytes
end

Public Instance Methods

bytes() click to toggle source

Return bytes

# File lib/support/bytes.rb, line 19
def bytes
  @bytes
end
unit() click to toggle source

Return unit name

# File lib/support/bytes.rb, line 24
def unit
  @unit||=set_unit
end
value() click to toggle source

Return unit value

# File lib/support/bytes.rb, line 29
def value
  @value||=set_value
end

Private Instance Methods

set_unit() click to toggle source
# File lib/support/bytes.rb, line 35
def set_unit
  count=self.value
  system_name=([@@default_unit]+@@units)[@power]
  I18n.t("lolita.support.bytes.#{system_name}",:count=>count)
end
set_value(val=nil) click to toggle source
# File lib/support/bytes.rb, line 41
def set_value(val=nil)
  operation_value=val ? val : self.bytes
  @@units.size.downto(1) do |pow|
    if operation_value>=(1024**pow)
      @power=pow 
      break
    end
  end
  result= (operation_value.to_f/(1024**@power).to_f).round(2)
  if val
    result
  else
    set_value(result*1024**@power)
  end
end