Skip to content

Commit

Permalink
add check to catch invalid units in the denominator, fixes issue olbr…
Browse files Browse the repository at this point in the history
  • Loading branch information
olbrich committed May 13, 2012
1 parent ba9ad59 commit e331b8c
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/ruby_units/unit.rb
Expand Up @@ -1433,6 +1433,7 @@ def parse(passed_unit_string="0")
return return
end end


# more than one per. I.e., "1 m/s/s"
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.count('/') > 1 raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.count('/') > 1
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.scan(/\s[02-9]/).size > 0 raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.scan(/\s[02-9]/).size > 0
@scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] #parse the string into parts @scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] #parse the string into parts
Expand All @@ -1456,8 +1457,10 @@ def parse(passed_unit_string="0")
@numerator = top.scan(Unit.unit_match_regex).delete_if {|x| x.empty?}.compact if top @numerator = top.scan(Unit.unit_match_regex).delete_if {|x| x.empty?}.compact if top
@denominator = bottom.scan(Unit.unit_match_regex).delete_if {|x| x.empty?}.compact if bottom @denominator = bottom.scan(Unit.unit_match_regex).delete_if {|x| x.empty?}.compact if bottom


us = "#{(top || '' + bottom || '')}".to_s.gsub(Unit.unit_match_regex,'').gsub(/[\d\*, "'_^\/\$]/,'') # eliminate all known terms from this string. This is a quick check to see if the passed unit
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") unless us.empty? # contains terms that are not defined.
used = "#{top} #{bottom}".to_s.gsub(Unit.unit_match_regex,'').gsub(/[\d\*, "'_^\/\$]/,'')
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") unless used.empty?


@numerator = @numerator.map do |item| @numerator = @numerator.map do |item|
@@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]] @@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]
Expand Down
1 change: 1 addition & 0 deletions spec/ruby-units/unit_spec.rb
Expand Up @@ -553,6 +553,7 @@


specify "no undefined units" do specify "no undefined units" do
expect {Unit("1 mFoo")}.to raise_error(ArgumentError,"'1 mFoo' Unit not recognized") expect {Unit("1 mFoo")}.to raise_error(ArgumentError,"'1 mFoo' Unit not recognized")
expect {Unit("1 second/mFoo")}.to raise_error(ArgumentError,"'1 second/mFoo' Unit not recognized")
end end


specify "no units with powers greater than 19" do specify "no units with powers greater than 19" do
Expand Down

0 comments on commit e331b8c

Please sign in to comment.