2008-07-14 20:50:32 -04:00
|
|
|
require 'abstract_unit'
|
|
|
|
|
|
|
|
uses_mocha 'Memoizable' do
|
|
|
|
class MemoizableTest < Test::Unit::TestCase
|
|
|
|
class Person
|
2008-07-18 16:32:28 -04:00
|
|
|
extend ActiveSupport::Memoizable
|
2008-07-14 20:50:32 -04:00
|
|
|
|
|
|
|
def name
|
|
|
|
fetch_name_from_floppy
|
|
|
|
end
|
|
|
|
|
2008-07-18 16:32:28 -04:00
|
|
|
memoize :name
|
|
|
|
|
2008-07-14 20:50:32 -04:00
|
|
|
def age
|
|
|
|
nil
|
|
|
|
end
|
2008-07-18 12:18:16 -04:00
|
|
|
|
2008-07-18 16:32:28 -04:00
|
|
|
def counter
|
|
|
|
@counter ||= 0
|
|
|
|
@counter += 1
|
2008-07-18 12:18:16 -04:00
|
|
|
end
|
|
|
|
|
2008-07-18 16:32:28 -04:00
|
|
|
memoize :age, :counter
|
2008-07-14 20:50:32 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
def fetch_name_from_floppy
|
|
|
|
"Josh"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2008-07-18 12:18:16 -04:00
|
|
|
def setup
|
|
|
|
@person = Person.new
|
|
|
|
end
|
|
|
|
|
2008-07-14 20:50:32 -04:00
|
|
|
def test_memoization
|
2008-07-18 12:18:16 -04:00
|
|
|
assert_equal "Josh", @person.name
|
|
|
|
|
|
|
|
@person.expects(:fetch_name_from_floppy).never
|
|
|
|
2.times { assert_equal "Josh", @person.name }
|
|
|
|
end
|
2008-07-14 20:50:32 -04:00
|
|
|
|
2008-07-18 12:18:16 -04:00
|
|
|
def test_reloadable
|
2008-07-18 16:32:28 -04:00
|
|
|
counter = @person.counter
|
|
|
|
assert_equal 1, @person.counter
|
|
|
|
assert_equal 2, @person.counter(:reload)
|
2008-07-14 20:50:32 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def test_memoized_methods_are_frozen
|
2008-07-18 12:18:16 -04:00
|
|
|
assert_equal true, @person.name.frozen?
|
|
|
|
|
|
|
|
@person.freeze
|
|
|
|
assert_equal "Josh", @person.name
|
|
|
|
assert_equal true, @person.name.frozen?
|
2008-07-14 20:50:32 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def test_memoization_frozen_with_nil_value
|
2008-07-18 12:18:16 -04:00
|
|
|
@person.freeze
|
|
|
|
assert_equal nil, @person.age
|
2008-07-14 20:50:32 -04:00
|
|
|
end
|
2008-07-14 21:23:23 -04:00
|
|
|
|
|
|
|
def test_double_memoization
|
|
|
|
assert_raise(RuntimeError) { Person.memoize :name }
|
|
|
|
end
|
2008-07-18 16:32:28 -04:00
|
|
|
|
|
|
|
class Company
|
|
|
|
def name
|
|
|
|
lookup_name
|
|
|
|
end
|
|
|
|
|
|
|
|
def lookup_name
|
|
|
|
"37signals"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def test_object_memoization
|
|
|
|
company = Company.new
|
|
|
|
company.extend ActiveSupport::Memoizable
|
|
|
|
company.memoize :name
|
|
|
|
|
|
|
|
assert_equal "37signals", company.name
|
|
|
|
# Mocha doesn't play well with frozen objects
|
|
|
|
company.metaclass.instance_eval { define_method(:lookup_name) { b00m } }
|
|
|
|
assert_equal "37signals", company.name
|
|
|
|
|
|
|
|
assert_equal true, company.name.frozen?
|
|
|
|
company.freeze
|
|
|
|
assert_equal true, company.name.frozen?
|
|
|
|
end
|
2008-07-14 20:50:32 -04:00
|
|
|
end
|
|
|
|
end
|