diff --git a/lib/cached/config_compiler.rb b/lib/cached/config_compiler.rb index fb2f5ba..7542961 100644 --- a/lib/cached/config_compiler.rb +++ b/lib/cached/config_compiler.rb @@ -57,12 +57,16 @@ def compiled_fetch_method_for(index) method_suffix_and_parameters = "#{index_name}(#{index.join(', ')})" - delegates = @config.delegates.collect { |delegate| "#{delegate}_by_#{method_suffix_and_parameters}" } + delegation = @config.delegates.collect { |delegate| "|| #{delegate}_by_#{method_suffix_and_parameters}" } "def self.lookup_by_#{method_suffix_and_parameters};" + - " key = Cached.store.read(#{cache_key}); "+ - #}" key ? Cached.store.read(key): Cached.store.fetch(key) { #{ delegates.join(' || ') } } ;" + - " key ? lookup(key): nil;" + + " if key = Cached.store.read(#{cache_key});"+ + " lookup(key);"+ + " else;"+ + " obj = nil #{delegation};" + + " obj.save_indexes_to_cache if obj.respond_to?(:save_indexes_to_cache);" + + " obj;" + + " end;" + "end;" end diff --git a/test/test_record.rb b/test/test_record.rb index e05950b..adf0104 100644 --- a/test/test_record.rb +++ b/test/test_record.rb @@ -16,7 +16,7 @@ def name index :last_name index [:first_name, :last_name] - #delegate_to :find + delegate_to :find end end @@ -26,14 +26,26 @@ def setup @bob = Person.create(:first_name => 'Bob', :last_name => 'Bobsen') end + test "cachemiss delegates to find" do + assert !Cached.store.read("person:1") + assert_equal @bob, Person.lookup(@bob.id) + end + test "load bob from cache store" do @bob.save_to_cache - assert_equal @bob, Person.find_by_first_name('Bob') - assert_equal @bob, Person.find_by_last_name('Bobsen') - assert_equal @bob, Person.find_by_first_name_and_last_name('Bob', 'Bobsen') - + assert_equal @bob, Person.lookup_by_first_name('Bob') + assert_equal @bob, Person.lookup_by_last_name('Bobsen') + assert_equal @bob, Person.lookup_by_first_name_and_last_name('Bob', 'Bobsen') end + + test "cache miss on index query will make returned object re-save its indexes" do + assert !Cached.store.read("person/first_name:#{hash('Bob')}") + assert_equal @bob, Person.lookup_by_first_name('Bob') + + assert Cached.store.read("person/first_name:#{hash('Bob')}") + end + private