[#4604] Add basic caching for TimeEntry#cost

This commit is contained in:
Eric Davis
2010-10-06 12:12:45 -07:00
parent cec35ad3af
commit dbfc6c5335
3 changed files with 66 additions and 8 deletions

View File

@@ -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

View File

@@ -20,15 +20,28 @@ module RateTimeEntryPatch
module InstanceMethods module InstanceMethods
# Returns the current cost of the TimeEntry based on it's rate and hours # Returns the current cost of the TimeEntry based on it's rate and hours
def cost def cost
if self.rate.nil? unless @cost
amount = Rate.amount_for(self.user, self.project, self.spent_on.to_s) if self.rate.nil?
else amount = Rate.amount_for(self.user, self.project, self.spent_on.to_s)
amount = rate.amount else
amount = rate.amount
end
if amount.nil?
@cost = 0.0
else
@cost = amount.to_f * hours.to_f
end
cache_cost
end end
return 0.0 if amount.nil? @cost
end
return amount.to_f * hours.to_f
def cache_cost
@cost ||= cost
update_attribute(:cost, @cost)
end end
end end
end end

View File

@@ -5,7 +5,7 @@ class RateTimeEntryPatchTest < ActiveSupport::TestCase
@user = User.generate! @user = User.generate!
@project = Project.generate! @project = Project.generate!
@date = Date.today.to_s @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 end
should 'should return 0.0 if there are no rates for the user' do should 'should return 0.0 if there are no rates for the user' do
@@ -26,4 +26,40 @@ class RateTimeEntryPatchTest < ActiveSupport::TestCase
end 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 end