[#5734] Fix the cost caching case where Time Entry attributes changed
A cost value wasn't getting recaclulated by TimeEntry#cost when the attributes were changing. It only was recalculated when .cost changed.
This commit is contained in:
@@ -9,7 +9,7 @@ module RateTimeEntryPatch
|
||||
unloadable # Send unloadable so it will not be unloaded in development
|
||||
belongs_to :rate
|
||||
|
||||
before_save :cost
|
||||
before_save :recalculate_cost
|
||||
|
||||
end
|
||||
|
||||
@@ -32,7 +32,9 @@ module RateTimeEntryPatch
|
||||
# Returns the current cost of the TimeEntry based on it's rate and hours
|
||||
#
|
||||
# Is a read-through cache method
|
||||
def cost
|
||||
def cost(options={})
|
||||
store_to_db = options[:store] || false
|
||||
|
||||
unless read_attribute(:cost)
|
||||
if self.rate.nil?
|
||||
amount = Rate.amount_for(self.user, self.project, self.spent_on.to_s)
|
||||
@@ -43,8 +45,13 @@ module RateTimeEntryPatch
|
||||
if amount.nil?
|
||||
write_attribute(:cost, 0.0)
|
||||
else
|
||||
if store_to_db
|
||||
# Write the cost to the database for caching
|
||||
update_attribute(:cost, amount.to_f * hours.to_f)
|
||||
else
|
||||
# Cache to object only
|
||||
write_attribute(:cost, amount.to_f * hours.to_f)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -60,6 +67,12 @@ module RateTimeEntryPatch
|
||||
update_attribute(:cost, cost)
|
||||
end
|
||||
|
||||
def recalculate_cost
|
||||
clear_cost_cache
|
||||
cost(:store => false)
|
||||
true # for callback
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -71,6 +71,21 @@ class RateTimeEntryPatchTest < ActiveSupport::TestCase
|
||||
|
||||
assert_equal 2000.0, @time_entry.read_attribute(:cost)
|
||||
end
|
||||
|
||||
should "clear and recalculate the cache when the attribute is already set but stale" do
|
||||
# Set the cost
|
||||
assert @time_entry.save
|
||||
assert_equal 2000.0, @time_entry.read_attribute(:cost)
|
||||
|
||||
@time_entry.reload
|
||||
@time_entry.hours = 20
|
||||
assert @time_entry.save
|
||||
|
||||
assert_equal 4000.0, @time_entry.read_attribute(:cost)
|
||||
assert_equal 4000.0, @time_entry.reload.cost
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user