Module: Converter
- Included in:
- Calcpace
- Defined in:
- lib/calcpace/converter.rb
Overview
Module to convert between different units of distance and speed
This module provides conversion methods for 42 different unit pairs, including distance units (kilometers, miles, meters, feet, etc.) and speed units (m/s, km/h, mi/h, knots, etc.).
Defined Under Namespace
Constant Summary collapse
- DISTANCE_UNIT_TO_KM =
Multipliers from a supported distance-input unit to kilometres (used by methods that accept a distance_unit: keyword)
{ km: 1.0, mi: Distance::MI_TO_KM }.freeze
Instance Method Summary collapse
-
#constant(unit) ⇒ Float
Retrieves the conversion constant for a given unit.
-
#convert(value, unit) ⇒ Float
Converts a value from one unit to another.
-
#convert_to_clocktime(seconds) ⇒ String
Converts seconds to a clocktime string.
-
#convert_to_seconds(time) ⇒ Integer
Converts a time string to total seconds.
- #list_all ⇒ Object
- #list_distance ⇒ Object
- #list_speed ⇒ Object
Instance Method Details
#constant(unit) ⇒ Float
Retrieves the conversion constant for a given unit
123 124 125 126 127 128 129 130 131 132 |
# File 'lib/calcpace/converter.rb', line 123 def constant(unit) unit = format_unit(unit) if unit.is_a?(String) Distance.const_get(unit.to_s.upcase) rescue NameError begin Speed.const_get(unit.to_s.upcase) rescue NameError raise Calcpace::UnsupportedUnitError, unit end end |
#convert(value, unit) ⇒ Float
Converts a value from one unit to another
72 73 74 75 76 |
# File 'lib/calcpace/converter.rb', line 72 def convert(value, unit) check_positive(value, 'Value') unit_constant = constant(unit) value * unit_constant end |
#convert_to_clocktime(seconds) ⇒ String
Converts seconds to a clocktime string
108 109 110 111 112 |
# File 'lib/calcpace/converter.rb', line 108 def convert_to_clocktime(seconds) days = seconds / 86_400 format = days.to_i.positive? ? "#{days} %H:%M:%S" : '%H:%M:%S' Time.at(seconds).utc.strftime(format) end |
#convert_to_seconds(time) ⇒ Integer
Converts a time string to total seconds
86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/calcpace/converter.rb', line 86 def convert_to_seconds(time) parts = time.split(':').map(&:to_i) case parts.length when 2 minute, seconds = parts (minute * 60) + seconds when 3 hour, minute, seconds = parts (hour * 3600) + (minute * 60) + seconds else 0 end end |
#list_all ⇒ Object
134 135 136 |
# File 'lib/calcpace/converter.rb', line 134 def list_all format_list(Distance.constants + Speed.constants) end |
#list_distance ⇒ Object
142 143 144 |
# File 'lib/calcpace/converter.rb', line 142 def list_distance format_list(Distance.constants) end |
#list_speed ⇒ Object
138 139 140 |
# File 'lib/calcpace/converter.rb', line 138 def list_speed format_list(Speed.constants) end |