Skip to content

Commit

Permalink
now rewrites the indexes to cache on cache miss + delegation hit
Browse files Browse the repository at this point in the history
  • Loading branch information
Tobias Lütke committed Jun 8, 2009
1 parent 1b5eb1f commit a5ede8a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
12 changes: 8 additions & 4 deletions lib/cached/config_compiler.rb
Expand Up @@ -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

Expand Down
22 changes: 17 additions & 5 deletions test/test_record.rb
Expand Up @@ -16,7 +16,7 @@ def name
index :last_name
index [:first_name, :last_name]

#delegate_to :find
delegate_to :find
end
end

Expand All @@ -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

Expand Down

0 comments on commit a5ede8a

Please sign in to comment.