Method: UnitMeasurements::ConversionMethods.define_conversion_method_for

Defined in:
lib/unit_measurements/extras/conversion_methods.rb

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

Defines conversion methods for a specific unit within a unit_group. These methods are defined dynamically using define_method.

Parameters:

  • unit (String|Symbol|Unit)

    The unit (or its name) for which the conversion methods need to be defined.

  • unit_group (UnitGroup)

    The unit group to which the unit belongs.

Returns:

  • (Unit)

    The unit instance for which the conversion methods were defined.

See Also:

Since:

  • 5.15.0



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

def define_conversion_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]+$/

    define_method("in_#{method_name}") do |use_cache: false|
      convert_to(unit, use_cache: use_cache)
    end
    alias_method "to_#{method_name}", "in_#{method_name}"
    alias_method "as_#{method_name}", "in_#{method_name}"
  end

  unit
end