Permalink
Browse files

Fix memoize_all for methods with punctuation [#1175 state:resolved]

Signed-off-by: Joshua Peek <josh@joshpeek.com>
  • Loading branch information...
1 parent 1c75b4f commit 8603813ac6e1bff8d3addad58d0a56b33baafc59 @libc libc committed with josh Oct 5, 2008
Showing with 12 additions and 3 deletions.
  1. +7 −3 activesupport/lib/active_support/memoizable.rb
  2. +5 −0 activesupport/test/memoizable_test.rb
View
10 activesupport/lib/active_support/memoizable.rb
@@ -1,5 +1,9 @@
module ActiveSupport
module Memoizable
+ MEMOIZED_IVAR = Proc.new do |symbol|
+ "@_memoized_#{symbol.to_s.sub(/\?\Z/, '_query').sub(/!\Z/, '_bang')}".to_sym
@djd
djd Oct 8, 2008

What about using __query and __bang?

+ end
+
module Freezable
def self.included(base)
base.class_eval do
@@ -20,7 +24,7 @@ def memoize_all
if method(m).arity == 0
__send__($1)
else
- ivar = :"@_memoized_#{$1}"
+ ivar = MEMOIZED_IVAR.call($1)
instance_variable_set(ivar, {})
end
end
@@ -30,7 +34,7 @@ def memoize_all
def unmemoize_all
methods.each do |m|
if m.to_s =~ /^_unmemoized_(.*)/
- ivar = :"@_memoized_#{$1}"
+ ivar = MEMOIZED_IVAR.call($1)
instance_variable_get(ivar).clear if instance_variable_defined?(ivar)
end
end
@@ -40,7 +44,7 @@ def unmemoize_all
def memoize(*symbols)
symbols.each do |symbol|
original_method = :"_unmemoized_#{symbol}"
- memoized_ivar = :"@_memoized_#{symbol.to_s.sub(/\?\Z/, '_query').sub(/!\Z/, '_bang')}"
+ memoized_ivar = MEMOIZED_IVAR.call(symbol)
class_eval <<-EOS, __FILE__, __LINE__
include Freezable
View
5 activesupport/test/memoizable_test.rb
@@ -100,6 +100,11 @@ def test_memoization
def test_memoization_with_punctuation
assert_equal true, @person.name?
+
+ assert_nothing_raised(NameError) do
+ @person.memoize_all
+ @person.unmemoize_all
+ end
end
def test_memoization_with_nil_value

5 comments on commit 8603813

@ijayasin

Josh, would this not cause a clash between “something?” and “something_query” as well as “something_else!” and “something_else_bang”, (although the latter is less likely to occur) ?

@josh
Ruby on Rails member

Probably, but its more realistic to assume that people are using “save!” over “save_bang”.

@adkron

Can’t you put a space in the method name, and then no one will be able to call it unless they use send or something similar, and at that point they are being very intentional.

@josh
Ruby on Rails member

We could do that for methods but not instance variables. Instance variables can’t have spaces, nor symbols like ‘!’.

@adkron

Yeah, not thinking. Sorry.

Please sign in to comment.