Module: BytesConverter

Defined in:
lib/bytes_converter.rb,
lib/bytes_converter/version.rb

Constant Summary collapse

VERSION =
"0.0.5"

Class Method Summary collapse

Class Method Details

.add_unit(new_unit) ⇒ Object

method adding new unit to @sizes hash



41
42
43
44
# File 'lib/bytes_converter.rb', line 41

def self.add_unit new_unit
  @sizes.merge!(new_unit)
  true
end

.convert(size) ⇒ Object

method converting size into bytes



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/bytes_converter.rb', line 13

def self.convert size

  # replacing comma with dot
  size_converted = size.downcase.gsub(',','.')

  # separating digits (size) from rest of the string (unit)
  x = size_converted.scan(/(\d*\.?\d*)(.*)/).collect { |found| found }

  # stripping whitespaces
  x[0][0].strip!
  x[0][1].strip!

  # limiting unit to first letter (k,m and so on)
  x[0][1] = x[0][1][/\w{1}/]

  # if unit is present (not nil) -> getting multiplier from sizes array
  # and calculating bytes
  unless x[0][1].nil?
    out = x[0][0].to_f * @sizes[x[0][1]].to_f
  else # if unit is not present -> we assume that size is already in bytes.
    out = x[0][0].to_f
  end

  # returning calculated (or not) value
  out
end

.get_unitsObject

getter for sizes



47
48
49
# File 'lib/bytes_converter.rb', line 47

def self.get_units
  @sizes
end

.remove_unit(unit) ⇒ Object

method removing size



52
53
54
# File 'lib/bytes_converter.rb', line 52

def self.remove_unit unit
  @sizes.delete(unit) { |key| "Unit \"#{key}\" not found among sizes!" }
end