diff --git a/lib/rate_time_entry_patch.rb b/lib/rate_time_entry_patch.rb index 3cd3267..f37ad9e 100644 --- a/lib/rate_time_entry_patch.rb +++ b/lib/rate_time_entry_patch.rb @@ -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 - # Write the cost to the database for caching - update_attribute(:cost, amount.to_f * hours.to_f) + 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 @@ -59,6 +66,12 @@ module RateTimeEntryPatch clear_cost_cache update_attribute(:cost, cost) end + + def recalculate_cost + clear_cost_cache + cost(:store => false) + true # for callback + end end end diff --git a/test/unit/lib/rate_time_entry_patch_test.rb b/test/unit/lib/rate_time_entry_patch_test.rb index 76c5afd..bbc9ad4 100644 --- a/test/unit/lib/rate_time_entry_patch_test.rb +++ b/test/unit/lib/rate_time_entry_patch_test.rb @@ -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