Module: UnitMeasurements::NumericMethods

Included in:
Measurement
Defined in:
lib/unit_measurements/extras/numeric_methods.rb

Overview

This module provides methods to define Numeric methods for a list of units within a unit group. If units are empty, it defaults to defining methods for all units in the unit group.

This module is included in the Measurement class to allow defining numeric methods for specified units.

See Also:

Author:

Since:

  • 5.14.0

Class Method Summary collapse

Class Method Details

.define_numeric_method_for(unit, unit_group) ⇒ Unit (private)

Defines a numeric method for a specific unit within a unit_group. The method is defined dynamically using define_method and associates the unit with the numeric value.

Parameters:

  • unit (String|Symbol|Unit)

    The unit (or its name) for which the numeric method needs to be defined.

  • unit_group (UnitGroup)

    The unit group to which the unit belongs.

Returns:

  • (Unit)

    The unit instance for which the method was defined.

See Also:

Author:

Since:

  • 5.14.0



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/unit_measurements/extras/numeric_methods.rb', line 70

def define_numeric_method_for(unit, unit_group)
  unit = unit.is_a?(Unit) ? unit : unit_group.unit_for!(unit)

  unit.names.each do |method_name|
    # Check if the name contains alphabetic characters
    next unless method_name =~ /^[a-zA-Z]+$/

    Numeric.define_method(method_name) do
      unit_group.new(self, unit)
    end
  end

  unit
end

.define_numeric_methods(*units) ⇒ Array<Unit>

Note:

This method defines a numeric methods specifically for units that contain alphabetic characters in their names.

Defines Numeric methods for specified units within the unit group. If units are empty, it defaults to defining methods for all units within the unit group.

Examples:

Define numeric methods for metres, centimetres, and millimetres:

UnitMeasurements::Length.define_numeric_methods("metres", :cm, :mm)

Define numeric methods for all units within the unit group:

UnitMeasurements::Length.define_numeric_methods

Parameters:

  • units (Array<String|Symbol>, optional)

    An array of units’ names for which numeric methods need to be defined. If empty, methods will be defined for all units within the unit group.

Returns:

  • (Array<Unit>)

    An array of units for which numeric methods were defined.

See Also:

Author:

Since:

  • 5.14.0



43
44
45
46
47
48
49
50
# File 'lib/unit_measurements/extras/numeric_methods.rb', line 43

def define_numeric_methods(*units)
  unit_group = self
  units = units.empty? ? unit_group.units : units

  units.inject([]) do |units, unit|
    units << define_numeric_method_for(unit, unit_group)
  end
end