Skip to content
Browse files

add check to catch invalid units in the denominator, fixes issue #41

  • Loading branch information...
1 parent ba9ad59 commit e331b8cd69e15ecda0118b2a64043cac08d8acde @olbrich olbrich committed May 13, 2012
Showing with 6 additions and 2 deletions.
  1. +5 −2 lib/ruby_units/unit.rb
  2. +1 −0 spec/ruby-units/unit_spec.rb
View
7 lib/ruby_units/unit.rb
@@ -1433,6 +1433,7 @@ def parse(passed_unit_string="0")
return
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.scan(/\s[02-9]/).size > 0
@scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] #parse the string into parts
@@ -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
@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\*, "'_^\/\$]/,'')
- raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") unless us.empty?
+ # eliminate all known terms from this string. This is a quick check to see if the passed unit
+ # 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|
@@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]
View
1 spec/ruby-units/unit_spec.rb
@@ -553,6 +553,7 @@
specify "no undefined units" do
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
specify "no units with powers greater than 19" do

0 comments on commit e331b8c

Please sign in to comment.
Something went wrong with that request. Please try again.