Commit dc0687d
Changed files (2)
app
models
spec
models
app/models/quantity.rb
@@ -14,42 +14,47 @@ class Quantity
@amount.to_f
end
- def eql?(other)
+ def eql?(other, delta = 0.1)
converted = other.to(unit)
- self.amount == converted
+ (self.amount - converted.amount).abs <= delta
end
def to_s
to_f.to_s
end
-end
-
-class Unit
- def self.for(unit)
- case unit
- when :lbs, :lb
- Pound.new
- when :kg, :kgs
- Kilogram.new
+ class Unit
+ def self.for(unit)
+ case unit
+ when :lbs, :lb
+ Pound.new
+ when :kg, :kgs
+ Kilogram.new
+ else
+ unit
+ end
end
end
-end
-class Pound < Unit
- def convert(amount, unit)
- if unit.is_a? Kilogram
- amount * 2.20462
+ class Pound < Unit
+ def convert(amount, unit)
+ case unit
+ when Kilogram
+ amount * 2.20462
+ else
+ amount
+ end
end
end
-end
-class Kilogram < Unit
- def convert(amount, unit)
- if unit.is_a? Pound
- amount * 0.453592
- elsif unit.is_a? Kilogram
- amount
+ class Kilogram < Unit
+ def convert(amount, unit)
+ case unit
+ when Pound
+ amount * 0.453592
+ else
+ amount
+ end
end
end
end
spec/models/quantity_spec.rb
@@ -16,5 +16,30 @@ describe Quantity do
kgs = Quantity.new(61.2, :kgs)
expect(kgs.to(:lbs).to_f.round(0)).to eql(135)
end
+
+ it 'converts lbs to lbs' do
+ lbs = Quantity.new(135.0, :lbs)
+ expect(lbs.to(:lbs).to_f).to eql(135.0)
+ end
+ end
+
+ describe "#eql?" do
+ it 'is equal when both are lbs' do
+ quantity = Quantity.new(135.0, :lbs)
+ other = Quantity.new(135.0, :lbs)
+ expect(quantity).to eql(other)
+ end
+
+ it 'is equal when both are kgs' do
+ quantity = Quantity.new(61.2, :kgs)
+ other = Quantity.new(61.2, :kgs)
+ expect(quantity).to eql(other)
+ end
+
+ it 'is equal when different units' do
+ quantity = Quantity.new(135.0, :lbs)
+ other = Quantity.new(61.2, :kgs)
+ expect(quantity).to eql(other)
+ end
end
end