Class: ChupaText::SizeParser

Inherits:
Object
  • Object
show all
Defined in:
lib/chupa-text/size-parser.rb

Defined Under Namespace

Classes: InvalidSizeError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parse(size) ⇒ Object


30
31
32
# File 'lib/chupa-text/size-parser.rb', line 30

def parse(size)
  new.parse(size)
end

Instance Method Details

#parse(size) ⇒ Object


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/chupa-text/size-parser.rb', line 35

def parse(size)
  case size
  when /TB?\z/i
    scale = 1024 ** 4
    number_part = $PREMATCH
  when /GB?\z/i
    scale = 1024 ** 3
    number_part = $PREMATCH
  when /MB?\z/i
    scale = 1024 ** 2
    number_part = $PREMATCH
  when /KB?\z/i
    scale = 1024 ** 1
    number_part = $PREMATCH
  when /B?\z/i
    scale = 1
    number_part = $PREMATCH
  else
    scale = 1
    number_part = size
  end

  begin
    number = Float(number_part)
  rescue ArgumentError
    raise InvalidSizeError.new(size)
  end
  (number * scale).round
end