Class: LighterpackParser::GramConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/lighterpack_parser/gram_converter.rb

Overview

Simple converter for weight units to grams.

Constant Summary collapse

CONVERSION_FACTORS =

Conversion factors for weight units to grams.

{
  'oz' => 28.3495,
  'lb' => 453.592,
  'g' => 1.0,
  'kg' => 1000.0
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_unit:) ⇒ GramConverter

Initialize the converter with the source unit.

Parameters:

  • source_unit (String)

    The unit to convert from.



17
18
19
# File 'lib/lighterpack_parser/gram_converter.rb', line 17

def initialize(source_unit:)
  @source_unit = source_unit
end

Class Method Details

.to_grams(value, unit) ⇒ Float

Convert a value from a unit to grams.

Parameters:

  • value (Float)

    The value to convert.

  • unit (String)

    The unit to convert from.

Returns:

  • (Float)

    The converted value in grams.



35
36
37
# File 'lib/lighterpack_parser/gram_converter.rb', line 35

def self.to_grams(value, unit)
  new(source_unit: unit).convert(value)
end

Instance Method Details

#convert(value) ⇒ Float

Convert a value from the source unit to grams.

Parameters:

  • value (Float)

    The value to convert..

Returns:

  • (Float)

    The converted value in grams.



25
26
27
28
# File 'lib/lighterpack_parser/gram_converter.rb', line 25

def convert(value)
  factor = CONVERSION_FACTORS[@source_unit.to_s.downcase] || 1.0
  value * factor
end