From 61a7cd75ac7724c3d28a7ea90e7507b4665b1077 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lennart=20L=C3=B6vstrand?= Date: Sat, 27 Aug 2022 22:41:21 +0200 Subject: [PATCH] Fix for convert_to won't recognize temperature aliases as temperatures #251 (#252) Use generated regex for detecting temperatures instead of a hard-coded one when using `convert_to` with a String argument. Fixes #251 Co-authored-by: Kevin Olbrich --- lib/ruby_units/unit.rb | 5 ++++- spec/ruby_units/temperature_spec.rb | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/ruby_units/unit.rb b/lib/ruby_units/unit.rb index 46e295be..3ed78883 100644 --- a/lib/ruby_units/unit.rb +++ b/lib/ruby_units/unit.rb @@ -351,6 +351,9 @@ def self.prefix_regex @@prefix_regex ||= @@prefix_map.keys.sort_by { |prefix| [prefix.length, prefix] }.reverse.join('|') end + # Generates (and memoizes) a regexp matching any of the temperature units or their aliases. + # + # @return [RegExp] def self.temp_regex @@temp_regex ||= begin temp_units = %w[tempK tempC tempF tempR degK degC degF degR] @@ -1070,7 +1073,7 @@ def convert_to(other) return self if TrueClass === other return self if FalseClass === other - if (other.is_a?(Unit) && other.temperature?) || (other.is_a?(String) && other =~ /temp[CFRK]/) + if (other.is_a?(Unit) && other.temperature?) || (other.is_a?(String) && other =~ self.class.temp_regex) raise ArgumentError, 'Receiver is not a temperature unit' unless degree? start_unit = units diff --git a/spec/ruby_units/temperature_spec.rb b/spec/ruby_units/temperature_spec.rb index 2f7e8582..37f3fa3c 100644 --- a/spec/ruby_units/temperature_spec.rb +++ b/spec/ruby_units/temperature_spec.rb @@ -1,7 +1,7 @@ require File.dirname(__FILE__) + '/../spec_helper' describe 'temperatures' do - describe 'redfine display name' do + describe 'redefine display name' do before(:all) do Unit.redefine!('tempC') do |c| c.aliases = %w[tC tempC] @@ -106,6 +106,9 @@ specify { expect(RubyUnits::Unit.new('100 tK').convert_to('tempR')).to be_within(RubyUnits::Unit.new('0.01 degR')).of(RubyUnits::Unit.new('180 tempR')) } specify { expect(RubyUnits::Unit.new('32 tF').convert_to('tempC')).to eq(RubyUnits::Unit.new('0 tC')) } + + # See https://github.com/olbrich/ruby-units/issues/251 + specify { expect(RubyUnits::Unit.new('32 tF').convert_to('tC')).to eq(RubyUnits::Unit.new('0 tC')) } end end end