Permalink
Browse files

Add Memoizable#flush_cache to clear the cache of a specific method [#…

…1505 state:resolved]
  • Loading branch information...
1 parent 2fc6c7d commit 761a633a9c0a45d76ef3ed10da97e3696c3ded79 @josh josh committed Dec 3, 2008
Showing with 38 additions and 16 deletions.
  1. +28 −16 activesupport/lib/active_support/memoizable.rb
  2. +10 −0 activesupport/test/memoizable_test.rb
@@ -1,10 +1,10 @@
module ActiveSupport
module Memoizable
- MEMOIZED_IVAR = Proc.new do |symbol|
+ def self.memoized_ivar_for(symbol)
"@_memoized_#{symbol.to_s.sub(/\?\Z/, '_query').sub(/!\Z/, '_bang')}".to_sym
end
- module Freezable
+ module InstanceMethods
def self.included(base)
base.class_eval do
unless base.method_defined?(:freeze_without_memoizable)
@@ -19,23 +19,35 @@ def freeze_with_memoizable
end
def memoize_all
- methods.each do |m|
- if m.to_s =~ /^_unmemoized_(.*)/
- if method(m).arity == 0
- __send__($1)
- else
- ivar = MEMOIZED_IVAR.call($1)
- instance_variable_set(ivar, {})
+ prime_cache ".*"
+ end
+
+ def unmemoize_all
+ flush_cache ".*"
+ end
+
+ def prime_cache(*syms)
+ syms.each do |sym|
+ methods.each do |m|
+ if m.to_s =~ /^_unmemoized_(#{sym})/
+ if method(m).arity == 0
+ __send__($1)
+ else
+ ivar = ActiveSupport::Memoizable.memoized_ivar_for($1)
+ instance_variable_set(ivar, {})
+ end
end
end
end
end
- def unmemoize_all
- methods.each do |m|
- if m.to_s =~ /^_unmemoized_(.*)/
- ivar = MEMOIZED_IVAR.call($1)
- instance_variable_get(ivar).clear if instance_variable_defined?(ivar)
+ def flush_cache(*syms, &block)
+ syms.each do |sym|
+ methods.each do |m|
+ if m.to_s =~ /^_unmemoized_(#{sym})/
+ ivar = ActiveSupport::Memoizable.memoized_ivar_for($1)
+ instance_variable_get(ivar).clear if instance_variable_defined?(ivar)
+ end
end
end
end
@@ -44,10 +56,10 @@ def unmemoize_all
def memoize(*symbols)
symbols.each do |symbol|
original_method = :"_unmemoized_#{symbol}"
- memoized_ivar = MEMOIZED_IVAR.call(symbol)
+ memoized_ivar = ActiveSupport::Memoizable.memoized_ivar_for(symbol)
class_eval <<-EOS, __FILE__, __LINE__
- include Freezable
+ include InstanceMethods
raise "Already memoized #{symbol}" if method_defined?(:#{original_method})
alias #{original_method} #{symbol}
@@ -128,6 +128,16 @@ def test_reloadable
assert_equal 3, @calculator.counter
end
+ def test_flush_cache
+ assert_equal 1, @calculator.counter
+
+ assert @calculator.instance_variable_get(:@_memoized_counter).any?
+ @calculator.flush_cache(:counter)
+ assert @calculator.instance_variable_get(:@_memoized_counter).empty?
+
+ assert_equal 2, @calculator.counter
+ end
+
def test_unmemoize_all
assert_equal 1, @calculator.counter

0 comments on commit 761a633

Please sign in to comment.