Skip to content

Commit

Permalink
Fixed memoize with punctuation and freezing memoized methods with arg…
Browse files Browse the repository at this point in the history
…uments

Signed-off-by: Joshua Peek <josh@joshpeek.com>
  • Loading branch information
jeremy authored and josh committed Aug 7, 2008
1 parent 105093f commit a805766
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
15 changes: 11 additions & 4 deletions activesupport/lib/active_support/memoizable.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -10,9 +10,16 @@ def self.included(base)
end end


def freeze_with_memoizable def freeze_with_memoizable
methods.each do |method| unless frozen?
__send__($1) if method.to_s =~ /^_unmemoized_(.*)/ methods.each do |method|
end unless frozen? if method.to_s =~ /^_unmemoized_(.*)/
begin
__send__($1)
rescue ArgumentError
end
end
end
end


freeze_without_memoizable freeze_without_memoizable
end end
Expand All @@ -21,7 +28,7 @@ def freeze_with_memoizable
def memoize(*symbols) def memoize(*symbols)
symbols.each do |symbol| symbols.each do |symbol|
original_method = "_unmemoized_#{symbol}" original_method = "_unmemoized_#{symbol}"
memoized_ivar = "@_memoized_#{symbol}" memoized_ivar = "@_memoized_#{symbol.to_s.sub(/\?\Z/, '_query').sub(/!\Z/, '_bang')}"


class_eval <<-EOS, __FILE__, __LINE__ class_eval <<-EOS, __FILE__, __LINE__
include Freezable include Freezable
Expand Down
15 changes: 15 additions & 0 deletions activesupport/test/memoizable_test.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ def name
"Josh" "Josh"
end end


def name?
true
end
memoize :name?

def update(name)
"Joshua"
end
memoize :update

def age def age
@age_calls += 1 @age_calls += 1
nil nil
Expand Down Expand Up @@ -88,6 +98,10 @@ def test_memoization
assert_equal 1, @person.name_calls assert_equal 1, @person.name_calls
end end


def test_memoization_with_punctuation
assert_equal true, @person.name?
end

def test_memoization_with_nil_value def test_memoization_with_nil_value
assert_equal nil, @person.age assert_equal nil, @person.age
assert_equal 1, @person.age_calls assert_equal 1, @person.age_calls
Expand All @@ -114,6 +128,7 @@ def test_memoization_cache_is_different_for_each_instance
def test_memoized_is_not_affected_by_freeze def test_memoized_is_not_affected_by_freeze
@person.freeze @person.freeze
assert_equal "Josh", @person.name assert_equal "Josh", @person.name
assert_equal "Joshua", @person.update("Joshua")
end end


def test_memoization_with_args def test_memoization_with_args
Expand Down

0 comments on commit a805766

Please sign in to comment.