Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

in! and error messages improved

Unit(string) should not be called from Unit class
  • Loading branch information...
commit 4e60d8a142f14f6904c7dd97415024db96114999 1 parent 5b87217
@minad authored
Showing with 20 additions and 18 deletions.
  1. +6 −7 lib/unit/class.rb
  2. +3 −2 lib/unit/dsl.rb
  3. +11 −9 test/error_test.rb
View
13 lib/unit/class.rb
@@ -55,7 +55,7 @@ def /(other)
end
def +(other)
- raise TypeError, "Incompatible units: #{self.inspect} and #{other.inspect}" if !compatible?(other)
+ raise TypeError, "#{inspect} and #{other.inspect} are incompatible" if !compatible?(other)
a, b = coerce(other)
a, b = a.normalize, b.normalize
Unit.new(a.value + b.value, a.unit, system).in(self)
@@ -117,12 +117,11 @@ def in(unit)
(a / conversion).normalize * conversion
end
- def in!(unit_string)
- new_unit = self.in(unit_string)
- unless new_unit.unit == Unit(1, unit_string).unit
- raise TypeError, "Unexpected unit #{new_unit.inspect}, expected to be in #{unit_string}"
- end
- new_unit
+ def in!(unit)
+ a, b = coerce(unit)
+ result = self.in(b)
+ raise TypeError, "Unexpected #{result.inspect}, expected to be in #{b.inspect}" unless result.unit == b.unit
+ result
end
def inspect
View
5 lib/unit/dsl.rb
@@ -14,8 +14,9 @@ def self.method_name_to_unit(name)
end
def method_missing(name)
- if name.to_s =~ /^in_/
- self.in(Unit.method_name_to_unit($'))
+ if name.to_s =~ /^in_(.*?)(!?)$/
+ unit = Unit.method_name_to_unit($1)
+ $2.empty? ? self.in(unit) : self.in!(unit)
else
Unit.to_unit(Unit.method_name_to_unit(name), system) * self
end
View
20 test/error_test.rb
@@ -6,21 +6,23 @@
describe "Errors" do
describe "TypeError when adding incompatible units" do
it "should have a nice error message" do
- unit_1 = Unit(1, "meter")
- unit_2 = Unit(1, "second")
- lambda {
- unit_1 + unit_2
- }.should.raise(TypeError).message.should.equal("Incompatible units: #{unit_1.inspect} and #{unit_2.inspect}")
+ a = Unit(1, "meter")
+ b = Unit(1, "second")
+ lambda do
+ a + b
+ end.should.raise(TypeError).message.should.equal("#{a.inspect} and #{b.inspect} are incompatible")
end
end
describe "TypeError when trying to convert incompatible unit using #in!" do
it "should have a nice error message" do
unit = Unit(1000, "m / s")
- new_unit = "seconds"
- lambda {
- unit.in!(new_unit)
- }.should.raise(TypeError).message.should.equal(%{Unexpected unit Unit("1000/1 m.s^-1"), expected to be in seconds})
+ lambda do
+ unit.in!("seconds")
+ end.should.raise(TypeError).message.should.equal(%{Unexpected Unit("1000/1 m.s^-1"), expected to be in Unit("1 s")})
+ lambda do
+ unit.in_seconds!
+ end.should.raise(TypeError).message.should.equal(%{Unexpected Unit("1000/1 m.s^-1"), expected to be in Unit("1 s")})
end
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.