Module: Philiprehberger::HumanSize
- Defined in:
- lib/philiprehberger/human_size.rb,
lib/philiprehberger/human_size/version.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- SI_UNITS =
%w[B KB MB GB TB PB EB].freeze
- BINARY_UNITS =
%w[B KiB MiB GiB TiB PiB EiB].freeze
- SI_BASE =
1000- BINARY_BASE =
1024- PARSE_PATTERN =
/\A\s*(-?\d+(?:\.\d+)?)\s*([a-z]+)\s*\z/i- UNIT_FACTORS =
{ 'B' => 1, 'KB' => 1000, 'MB' => 1000**2, 'GB' => 1000**3, 'TB' => 1000**4, 'PB' => 1000**5, 'EB' => 1000**6, 'KIB' => 1024, 'MIB' => 1024**2, 'GIB' => 1024**3, 'TIB' => 1024**4, 'PIB' => 1024**5, 'EIB' => 1024**6 }.freeze
- VERSION =
'0.4.0'
Class Method Summary collapse
- .convert(bytes, unit:, precision: 2) ⇒ Object
- .format(bytes, binary: false, precision: 2) ⇒ Object
- .format_parts(bytes, binary: false, precision: 2) ⇒ Object
- .parse(string) ⇒ Object
- .valid?(string) ⇒ Boolean
Class Method Details
.convert(bytes, unit:, precision: 2) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/philiprehberger/human_size.rb', line 46 def convert(bytes, unit:, precision: 2) raise Error, 'bytes must be a Numeric' unless bytes.is_a?(Numeric) raise Error, 'unit must be a String' unless unit.is_a?(String) key = unit.upcase factor = UNIT_FACTORS[key] raise Error, "unknown unit: #{unit}" unless factor value = bytes.to_f / factor "#{sprintf("%.#{precision}f", value)} #{unit}" # rubocop:disable Style/FormatString end |
.format(bytes, binary: false, precision: 2) ⇒ Object
34 35 36 37 38 |
# File 'lib/philiprehberger/human_size.rb', line 34 def format(bytes, binary: false, precision: 2) parts = compute_parts(bytes, binary: binary, precision: precision) "#{format_value(parts[:value], parts[:unit_index], precision)} #{parts[:unit]}" end |
.format_parts(bytes, binary: false, precision: 2) ⇒ Object
40 41 42 43 44 |
# File 'lib/philiprehberger/human_size.rb', line 40 def format_parts(bytes, binary: false, precision: 2) parts = compute_parts(bytes, binary: binary, precision: precision) { value: parts[:value], unit: parts[:unit] } end |
.parse(string) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/philiprehberger/human_size.rb', line 58 def parse(string) raise Error, 'input must be a String' unless string.is_a?(String) match = PARSE_PATTERN.match(string.strip) raise Error, "cannot parse: #{string.inspect}" unless match number = match[1].to_f unit = match[2].upcase factor = UNIT_FACTORS[unit] raise Error, "unknown unit: #{match[2]}" unless factor (number * factor).round end |
.valid?(string) ⇒ Boolean
73 74 75 76 77 78 79 80 |
# File 'lib/philiprehberger/human_size.rb', line 73 def valid?(string) return false unless string.is_a?(String) parse(string) true rescue Error false end |