diff --git a/lib/rate_time_entry_patch.rb b/lib/rate_time_entry_patch.rb index 2a7fa0f..fa93f83 100644 --- a/lib/rate_time_entry_patch.rb +++ b/lib/rate_time_entry_patch.rb @@ -8,6 +8,9 @@ module RateTimeEntryPatch base.class_eval do unloadable # Send unloadable so it will not be unloaded in development belongs_to :rate + + before_save :clear_cost_cache + before_save :cache_cost end @@ -38,11 +41,21 @@ module RateTimeEntryPatch @cost end + + def clear_cost_cache + @cost = nil + write_attribute(:cost, nil) + end def cache_cost @cost ||= cost - update_attribute(:cost, @cost) + write_attribute(:cost, @cost) end + + def save_cached_cost + update_attribute(:cost, cost) + 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 10af714..6e48ee1 100644 --- a/test/unit/lib/rate_time_entry_patch_test.rb +++ b/test/unit/lib/rate_time_entry_patch_test.rb @@ -6,15 +6,16 @@ class RateTimeEntryPatchTest < ActiveSupport::TestCase @project = Project.generate! @date = Date.today.to_s @time_entry = TimeEntry.new({:user => @user, :project => @project, :spent_on => @date, :hours => 10.0, :activity => TimeEntryActivity.generate!}) + @rate = Rate.generate!(:user => @user, :project => @project, :date_in_effect => @date, :amount => 200.0) end should 'should return 0.0 if there are no rates for the user' do + @rate.destroy assert_equal 0.0, @time_entry.cost end context 'should return the product of hours by' do should 'the results of Rate.amount_for' do - Rate.generate!(:user => @user, :project => @project, :date_in_effect => @date, :amount => 200.0) assert_equal((200.0 * @time_entry.hours), @time_entry.cost) end @@ -29,7 +30,6 @@ class RateTimeEntryPatchTest < ActiveSupport::TestCase 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 @@ -62,4 +62,15 @@ class RateTimeEntryPatchTest < ActiveSupport::TestCase end + context "before save" do + should "clear and recalculate the cache" do + assert_equal nil, @time_entry.read_attribute(:cost) + + assert @time_entry.save + + assert_equal 2000.0, @time_entry.read_attribute(:cost) + end + end + + end