Module: UnitMeasurements::Formatter

Included in:
Measurement
Defined in:
lib/unit_measurements/formatter.rb

Overview

The UnitMeasurements::Formatter mixin module contains methods for formatting measurements into human-readable strings. It provides the ability to customize the output format based on user-defined preferences.

This module is included in the Measurement class to allow customization of the output of the measurements.

See Also:

Author:

Since:

  • 1.1.0

Constant Summary collapse

DEFAULT_FORMAT =

The default format used for formatting measurements. It is a format string containing placeholders for quantity and unit.

Since:

  • 1.1.0

"%.2<quantity>f %<unit>s".freeze

Instance Method Summary collapse

Instance Method Details

#format(format = nil) ⇒ String

Formats measurement to certain formatted string specified by format. If format is not specified, it uses DEFAULT_FORMAT for formatting the measurement.

The format method allows for customization of the output format of a measurement. It uses format placeholders for quantity and unit. If no custom format is provided, it will use the DEFAULT_FORMAT.

Examples:

UnitMeasurements::Length.new(1, "m").to("in").format
=> "39.37 in"

UnitMeasurements::Length.new(1, "m").to("in").format("%.4<quantity>f %<unit>s")
=> "39.3701 in"

Parameters:

  • format (String, optional) (defaults to: nil)

    The custom format string for formatting the measurement. If not provided, DEFAULT_FORMAT is used.

Returns:

  • (String)

    A formatted string representing the measurement.

See Also:

Author:

Since:

  • 1.1.0



45
46
47
48
49
# File 'lib/unit_measurements/formatter.rb', line 45

def format(format = nil)
  kwargs = {quantity: quantity, unit: unit.to_s}

  (format || DEFAULT_FORMAT) % kwargs
end