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
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
119 120 121 122 123 124 125 126 127 128 |
# File 'lib/calcpace/converter.rb', line 119 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
68 69 70 71 72 |
# File 'lib/calcpace/converter.rb', line 68 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
104 105 106 107 108 |
# File 'lib/calcpace/converter.rb', line 104 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
82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/calcpace/converter.rb', line 82 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
130 131 132 |
# File 'lib/calcpace/converter.rb', line 130 def list_all format_list(Distance.constants + Speed.constants) end |
#list_distance ⇒ Object
138 139 140 |
# File 'lib/calcpace/converter.rb', line 138 def list_distance format_list(Distance.constants) end |
#list_speed ⇒ Object
134 135 136 |
# File 'lib/calcpace/converter.rb', line 134 def list_speed format_list(Speed.constants) end |