1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Add Memoizable#flush_cache to clear the cache of a specific method [#1505 state:resolved]

This commit is contained in:
Joshua Peek 2008-12-03 10:57:08 -06:00
parent 2fc6c7dd05
commit 761a633a9c
2 changed files with 38 additions and 16 deletions

View file

@ -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 @@ module ActiveSupport
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 @@ module ActiveSupport
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}

View file

@ -128,6 +128,16 @@ class MemoizableTest < Test::Unit::TestCase
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