Class: CompositeUnitMeasurements::Volume

Inherits:
Object
  • Object
show all
Defined in:
lib/composite_unit_measurements/volume.rb

Overview

A parser handling volume measurements, particularly for composite units like litre-millilitre, gallon-quart, quart-pint, etc.

Author:

Since:

  • 0.4.0

Constant Summary collapse

LITRE_ALIASES =

Regex pattern for aliases of litre unit.

Author:

Since:

  • 0.4.0

/(?:l|L|liter(?:s)?|litre(?:s)?)/.freeze
MILLILITRE_ALIASES =

Regex pattern for aliases of millilitre unit.

Author:

Since:

  • 0.4.0

/(?:ml|mL|milliliter(?:s)?|millilitre(?:s)?)/.freeze
LITRE_MILLILITRE =

Regex pattern for parsing a volume measurement in the format of litre-millilitre.

Author:

Since:

  • 0.4.0

/\A#{ANY_NUMBER}\s*#{LITRE_ALIASES}\s*#{ANY_NUMBER}\s*#{MILLILITRE_ALIASES}\z/.freeze

Class Method Summary collapse

Class Method Details

.parse(string) ⇒ UnitMeasurements::Volume

Parses a given string into a UnitMeasurements::Volume object.

Examples:

Parse ‘litre-millilitre’ measurement:

CompositeUnitMeasurements::Volume.parse("2 l 250 ml") #=> 2.25 l

Parameters:

  • string (String)

    The string to parse for volume measurement.

Returns:

  • (UnitMeasurements::Volume)

    Returns a UnitMeasurements::Volume object if parsing is successful.

Raises:

  • (UnitMeasurements::ParseError)

    If the string does not match any known format.

Author:

Since:

  • 0.4.0



29
30
31
32
33
34
# File 'lib/composite_unit_measurements/volume.rb', line 29

def parse(string)
  case string
  when LITRE_MILLILITRE then parse_litre_millilitre(string)
  else                       raise UnitMeasurements::ParseError, string
  end
end

.parse_litre_millilitre(string) ⇒ UnitMeasurements::Volume (private)

Parses a string representing a volume in the format of litre-millilitre into a UnitMeasurements::Volume object.

Parameters:

  • string (String)

    The string representing volume measurement in the format of litre-millilitre.

Returns:

  • (UnitMeasurements::Volume)

    Returns a UnitMeasurements::Volume object if parsing is successful.

See Also:

Author:

Since:

  • 0.4.0



50
51
52
53
54
55
56
# File 'lib/composite_unit_measurements/volume.rb', line 50

def parse_litre_millilitre(string)
  litre, millilitre = string.match(LITRE_MILLILITRE)&.captures

  if litre && millilitre
    UnitMeasurements::Volume.new(litre, "l") + UnitMeasurements::Volume.new(millilitre, "ml")
  end
end