Skip to content

Instantly share code, notes, and snippets.

@noahd1
Created February 5, 2010 08:17
Show Gist options
  • Save noahd1/295640 to your computer and use it in GitHub Desktop.
Save noahd1/295640 to your computer and use it in GitHub Desktop.
## assume a flushed memcache database
## and Sport.rb which has a cache-money index on :name
class Sport < ActiveRecord::Base
is_cached :repository => $cache
# This configuration enables calls to Sport.find_by_name("baseball") to come from and be written to a cache
index :name
end
## Let's try it
Sport.find_by_name("baseball")
## EXPECTED RESULT: SQL CALL: SELECT * FROM `sports` WHERE (`sports`.`name` = 'baseball')
## RESULT: SQL CALL: SELECT * FROM `sports` WHERE (`sports`.`name` = 'baseball')
# Cache is cold, so this is expected
# Second attempt
Sport.find_by_name("baseball")
## EXPECTED RESULT: NO SQL CALL (from cache)
## RESULT: SQL CALL: SELECT * FROM `sports` WHERE (`sports`.`id` = 49 AND (`sports`.`name` = 'baseball')) LIMIT 1
# Calls to Sport.find_by_name are not coming from the cache, even though we defined a cache money index for name.
# In fact, successive calls to find_by_name will do a memcache read but NEVER come from the cache ... UNLESS:
Sport.find(49) # the id of baseball
Sport.find_by_name("baseball")
## RESULT: NO SQL CALL (from cache)
## We've primed the result of the primary key finder into memcache and now successive calls to an indexed column will come out of the cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment