Commit b461b4f

mo khan <mo@mokhan.ca>
2016-06-25 17:08:51
add specs for conversions.
1 parent 81bb93f
Changed files (2)
app
spec
app/models/quantity.rb
@@ -3,12 +3,11 @@ class Quantity
 
   def initialize(amount, unit)
     @amount = amount
-    @unit = unit
+    @unit = Unit.for(unit)
   end
 
   def to(target_unit)
-    # TODO:: convert amount to target unit
-    @amount
+    Quantity.new(Unit.for(target_unit).convert(amount, unit), target_unit)
   end
 
   def to_f
@@ -24,3 +23,33 @@ class Quantity
     to_f.to_s
   end
 end
+
+
+class Unit
+  def self.for(unit)
+    case unit
+    when :lbs, :lb
+      Pound.new
+    when :kg, :kgs
+      Kilogram.new
+    end
+  end
+end
+
+class Pound < Unit
+  def convert(amount, unit)
+    if unit.is_a? Kilogram
+      amount * 2.20462
+    end
+  end
+end
+
+class Kilogram < Unit
+  def convert(amount, unit)
+    if unit.is_a? Pound
+      amount * 0.453592
+    elsif unit.is_a? Kilogram
+      amount
+    end
+  end
+end
spec/models/quantity_spec.rb
@@ -0,0 +1,20 @@
+require 'spec_helper'
+
+describe Quantity do
+  describe "#to" do
+    it 'converts lbs to kgs' do
+      lbs = Quantity.new(135.0, :lbs)
+      expect(lbs.to(:kg).to_f.round(1)).to eql(61.2)
+    end
+
+    it 'converts kgs to kgs' do
+      kgs = Quantity.new(135.0, :kgs)
+      expect(kgs.to(:kgs).to_f).to eql(135.0)
+    end
+
+    it 'converts kgs to lbs' do
+      kgs = Quantity.new(61.2, :kgs)
+      expect(kgs.to(:lbs).to_f.round(0)).to eql(135)
+    end
+  end
+end