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) ⇒ Object

Deprecated.

This method has been deprecated in favour of #to_fs.

This method is no longer recommended for use. Please use #to_fs instead.

Since:

  • 1.1.0



25
26
27
28
# File 'lib/unit_measurements/formatter.rb', line 25

def format(format = nil)
  warn "DEPRECATION WARNING: The `format` method is deprecated and will be removed in upcoming release. Please use `to_fs` instead."
  to_fs(format)
end

#to_fs(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 #to_fs method allows for customization of the output format of a measurement. It uses format placeholders for quantity and unit.

Examples:

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

UnitMeasurements::Length.new(1, "m").to("in").to_fs("%.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:

  • 5.10.0



53
54
55
56
# File 'lib/unit_measurements/formatter.rb', line 53

def to_fs(format = nil)
  kwargs = {quantity: quantity, unit: unit.to_s}
  (format || DEFAULT_FORMAT) % kwargs
end