Class: RubyPgExtras::SizeParser

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_pg_extras/size_parser.rb

Constant Summary collapse

SI_UNITS =
%w[bytes kB MB GB TB PB EB ZB YB].map(&:downcase).freeze
SI_REGEXP =
regexp_for_units(SI_UNITS)
BINARY_UNITS =
%w[bytes KiB MiB GiB TiB PiB EiB ZiB YiB].map(&:downcase).freeze
BINARY_REGEXP =
regexp_for_units(BINARY_UNITS)
DIGITS_ONLY_REGEXP =
/\A(-?\d+)\z/.freeze

Class Method Summary collapse

Class Method Details

.regexp_for_units(units) ⇒ Object



12
13
14
# File 'lib/ruby_pg_extras/size_parser.rb', line 12

def self.regexp_for_units(units)
  /\A(-?\d+)\s?(#{units.join('|')})\z/i
end

.to_i(arg) ⇒ Object

Raises:

  • (ArgumentError)


5
6
7
8
9
10
# File 'lib/ruby_pg_extras/size_parser.rb', line 5

def self.to_i(arg)
  value = to_i_si(arg) || to_i_binary(arg) || to_i_digits(arg)
  raise ArgumentError, "Unparseable size: #{arg}" if value.nil?

  value
end

.to_i_binary(arg) ⇒ Object



26
27
28
# File 'lib/ruby_pg_extras/size_parser.rb', line 26

def self.to_i_binary(arg)
  to_i_for_units(arg, BINARY_REGEXP, BINARY_UNITS, 1024)
end

.to_i_digits(arg) ⇒ Object



39
40
41
# File 'lib/ruby_pg_extras/size_parser.rb', line 39

def self.to_i_digits(arg)
  DIGITS_ONLY_REGEXP.match?(arg) ? arg.to_i : nil
end

.to_i_for_units(arg, regexp, units, multiplier) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/ruby_pg_extras/size_parser.rb', line 30

def self.to_i_for_units(arg, regexp, units, multiplier)
  match_data = regexp.match(arg)
  return nil unless match_data

  exponent = units.index(match_data[2].downcase).to_i
  match_data[1].to_i * multiplier**exponent
end

.to_i_si(arg) ⇒ Object



19
20
21
# File 'lib/ruby_pg_extras/size_parser.rb', line 19

def self.to_i_si(arg)
  to_i_for_units(arg, SI_REGEXP, SI_UNITS, 1000)
end