Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Reset association caches when returning from memory cache.

  • Loading branch information...
commit d13164057125d2714e6039373bf6de5c989b0d6b 1 parent f6b48af
@eric authored
View
18 lib/enumerate_by.rb
@@ -175,13 +175,13 @@ def find_all_by_enumerator!(enumerators)
#
# This allows for enumerations to permanently cache find queries, avoiding
# unnecessary lookups in the database.
- [:find_by_sql, :exists?, :calculate].each do |method|
+ [:find_every, :find_one, :exists?, :calculate].each do |method|
define_method(method) do |*args|
if EnumerateBy.perform_caching && perform_enumerator_caching
result = enumerator_cache_store.fetch([method] + args) { super(*args) }
# Call #dup on value returned from cache to undo the freezing that
# is done by the MemoryStore
- result.dup rescue result
+ clear_result_caches(result.dup) rescue result
else
super(*args)
end
@@ -212,6 +212,20 @@ def typecast_enumerator(enumerator)
enumerator.is_a?(Symbol) ? enumerator.to_s : enumerator
end
end
+
+ # Clear aggregation and association caches to act more like a normal
+ # ActiveRecord object
+ def clear_result_caches(result)
+ case result
+ when Array
+ result.each { |item| clear_result_caches(item) }
+ when ActiveRecord::Base
+ result.clear_aggregation_cache
+ result.clear_association_cache
+ end
+
+ result
+ end
end
module Bootstrapped
View
2  test/app_root/app/models/color.rb
@@ -1,3 +1,5 @@
class Color < ActiveRecord::Base
enumerate_by :name
+
+ has_many :cars
end
View
28 test/unit/assocations_test.rb
@@ -65,6 +65,34 @@ def test_should_have_exclusion_scope_for_multiple_enumerators
end
end
+class ModelWithHasManyTestWithCaching < ActiveRecord::TestCase
+ def setup
+ EnumerateBy.perform_caching = true
+
+ @red = create_color(:name => 'red')
+ @blue = create_color(:name => 'blue')
+ @red_car = create_car(:name => 'Ford Mustang', :color => @red)
+ @blue_car = create_car(:name => 'Ford Mustang', :color => @blue)
+ end
+
+ def teardown
+ EnumerateBy.perform_caching = false
+ end
+
+ def test_should_find_has_many_records
+ assert_equal [@red_car], Color['red'].cars
+ end
+
+ def test_should_find_changed_has_many_records
+ assert_equal [@red_car], Color['red'].cars
+
+ Car.delete_all
+ @red_honda = create_car(:name => 'Honda Accord', :color => @red)
+
+ assert_equal [@red_honda], Color['red'].cars
+ end
+end
+
class ModelWithPolymorphicBelongsToAssociationTest < ActiveRecord::TestCase
def test_should_not_create_named_scopes
assert !Car.respond_to?(:with_feature)
Please sign in to comment.
Something went wrong with that request. Please try again.