Permalink
Browse files

Ensure results returned by a memoized method are immutable

  • Loading branch information...
1 parent b8b3098 commit 8cb14ee1203c9ed380c4b192e8730757a52d43cb @josh josh committed Aug 14, 2008
Showing with 7 additions and 2 deletions.
  1. +2 −2 activesupport/lib/active_support/memoizable.rb
  2. +5 −0 activesupport/test/memoizable_test.rb
@@ -51,7 +51,7 @@ def memoize(*symbols)
if instance_method(:#{symbol}).arity == 0
def #{symbol}(reload = false)
if reload || !defined?(#{memoized_ivar}) || #{memoized_ivar}.empty?
- #{memoized_ivar} = [#{original_method}]
+ #{memoized_ivar} = [#{original_method}.freeze]
end
#{memoized_ivar}[0]
end
@@ -64,7 +64,7 @@ def #{symbol}(*args)
if !reload && #{memoized_ivar}.has_key?(args)
#{memoized_ivar}[args]
elsif #{memoized_ivar}
- #{memoized_ivar}[args] = #{original_method}(*args)
+ #{memoized_ivar}[args] = #{original_method}(*args).freeze
end
else
#{original_method}(*args)
@@ -110,6 +110,11 @@ def test_memoization_with_nil_value
assert_equal 1, @person.age_calls
end
+ def test_memorized_results_are_immutable
+ assert_equal "Josh", @person.name
+ assert_raise(ActiveSupport::FrozenObjectError) { @person.name.gsub!("Josh", "Gosh") }
+ end
+
def test_reloadable
counter = @calculator.counter
assert_equal 1, @calculator.counter

0 comments on commit 8cb14ee

Please sign in to comment.