Skip to content

Commit

Permalink
[#5734] Fix the cost caching case where Time Entry attributes changed
Browse files Browse the repository at this point in the history
A cost value wasn't getting recaclulated by TimeEntry#cost when the
attributes were changing. It only was recalculated when .cost changed.
  • Loading branch information
edavis10 committed Apr 6, 2011
1 parent b20ebe5 commit 4c3e6b6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/rate_time_entry_patch.rb
Expand Up @@ -9,7 +9,7 @@ def self.included(base) # :nodoc:
unloadable # Send unloadable so it will not be unloaded in development
belongs_to :rate

before_save :cost
before_save :recalculate_cost

end

Expand All @@ -32,7 +32,9 @@ module InstanceMethods
# 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)
Expand All @@ -43,8 +45,13 @@ def cost
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

Expand All @@ -59,6 +66,12 @@ def save_cached_cost
clear_cost_cache
update_attribute(:cost, cost)
end

def recalculate_cost
clear_cost_cache
cost(:store => false)
true # for callback
end

end
end
Expand Down
15 changes: 15 additions & 0 deletions test/unit/lib/rate_time_entry_patch_test.rb
Expand Up @@ -71,6 +71,21 @@ def setup

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


Expand Down

0 comments on commit 4c3e6b6

Please sign in to comment.