Module: UnitMeasurements::ConversionMethods
- Included in:
- Measurement
- Defined in:
- lib/unit_measurements/extras/conversion_methods.rb
Overview
This module provides functionality to define conversion 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. These methods allow easy conversion between different units within a given unit group.
This module is included in the Measurement
class to allow defining conversion methods for specified units.
Class Method Summary collapse
-
.define_conversion_method_for(unit, unit_group) ⇒ Unit
private
Defines conversion methods for a specific
unit
within aunit_group
. -
.define_conversion_methods(*units) ⇒ Array<Unit>
Defines conversion methods for specified
units
within the unit group.
Class Method Details
.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
.
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 |
.define_conversion_methods(*units) ⇒ Array<Unit>
This method defines a conversion methods specifically for units that contain alphabetic characters in their names.
Defines conversion methods for specified units
within the unit group. If units
are empty, it defaults to defining methods for all units within the unit group.
44 45 46 47 48 49 50 51 |
# File 'lib/unit_measurements/extras/conversion_methods.rb', line 44 def define_conversion_methods(*units) unit_group = self units = units.empty? ? unit_group.units : units units.inject([]) do |units, unit| units << define_conversion_method_for(unit, unit_group) end end |