Permalink
Browse files

[#4604] Add basic caching for TimeEntry#cost

  • Loading branch information...
1 parent cec35ad commit dbfc6c5335f53453d7f5823b8f5f3b88034920f3 @edavis10 committed Oct 6, 2010
@@ -0,0 +1,9 @@
+class AddCostToTimeEntries < ActiveRecord::Migration
+ def self.up
+ add_column :time_entries, :cost, :decimal, :precision => 15, :scale => 2
+ end
+
+ def self.down
+ remove_column :time_entries, :cost
+ end
+end
@@ -20,15 +20,28 @@ module ClassMethods
module InstanceMethods
# Returns the current cost of the TimeEntry based on it's rate and hours
def cost
- if self.rate.nil?
- amount = Rate.amount_for(self.user, self.project, self.spent_on.to_s)
- else
- amount = rate.amount
+ unless @cost
+ if self.rate.nil?
+ amount = Rate.amount_for(self.user, self.project, self.spent_on.to_s)
+ else
+ amount = rate.amount
+ end
+
+ if amount.nil?
+ @cost = 0.0
+ else
+ @cost = amount.to_f * hours.to_f
+ end
+
+ cache_cost
end
- return 0.0 if amount.nil?
-
- return amount.to_f * hours.to_f
+ @cost
+ end
+
+ def cache_cost
+ @cost ||= cost
+ update_attribute(:cost, @cost)
end
end
end
@@ -5,7 +5,7 @@ def setup
@user = User.generate!
@project = Project.generate!
@date = Date.today.to_s
- @time_entry = TimeEntry.new({:user => @user, :project => @project, :spent_on => @date, :hours => 10.0})
+ @time_entry = TimeEntry.new({:user => @user, :project => @project, :spent_on => @date, :hours => 10.0, :activity => TimeEntryActivity.generate!})
end
should 'should return 0.0 if there are no rates for the user' do
@@ -26,4 +26,40 @@ def setup
end
+ context "#cost" do
+ setup do
+ @time_entry.save!
+ Rate.generate!(:user => @user, :project => @project, :date_in_effect => @date, :amount => 200.0)
+ end
+
+ context "without a cache" do
+ should "return the calculated cost" do
+ @time_entry.update_attribute(:cost, nil)
+ assert_equal 2000.0, @time_entry.cost
+ end
+
+ should "cache the cost to the field" do
+ @time_entry.update_attribute(:cost, nil)
+ @time_entry.cost
+
+ assert_equal 2000.0, @time_entry.read_attribute(:cost)
+ assert_equal 2000.0, @time_entry.reload.read_attribute(:cost)
+ end
+
+ end
+
+ context "with a cache" do
+ setup do
+ @time_entry.cache_cost
+ end
+
+ should "return the cached cost" do
+ assert_equal 2000.0, @time_entry.read_attribute(:cost)
+ assert_equal 2000.0, @time_entry.cost
+ end
+
+ end
+
+ end
+
end

0 comments on commit dbfc6c5

Please sign in to comment.