Skip to content

Commit

Permalink
Fix for convert_to won't recognize temperature aliases as temperatures
Browse files Browse the repository at this point in the history
…#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 <[email protected]>
  • Loading branch information
lenlo authored Aug 27, 2022
1 parent 3120be3 commit 61a7cd7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
5 changes: 4 additions & 1 deletion lib/ruby_units/unit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion spec/ruby_units/temperature_spec.rb
Original file line number Diff line number Diff line change
@@ -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]
Expand Down Expand Up @@ -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

0 comments on commit 61a7cd7

Please sign in to comment.