I thought there was some kind of fancy voodoo happening, but it turns out that it’s basically just a hash! Memcached is simply a key value stored in memory, no voodoo here.
To implement just set your cache in,/config/environments/production.rb
config.cache_store = :mem_cache_store
Same thing as config.cache_store = :memory_store, but it runs as a separate process. You can have several rails instances that reference the same memcached instance.
Note: Please make sure to install the gem memcached in your environment.
Rails automatically creates a global cache during initialization and you can access this in your code either using Rails.cache or the RAILS_CACHE global variable.
We can use memcached as a fragment cache store or an object store.
Action & Fragment Caching
If we look into our memcached process we can see the keys that are getting stored inside the memcached. Then if we refresh our page we can see that the cached fragments are getting pulled.
Object Store
You can access the cache stores for storing queries strings
Rails.cache.read(
"name"
)
# => nil
Rails.cache.write(
"name"
,
"Bill"
)
Rails.cache.read(
"name"
)
# => "Bill"
Rails.cache.exist?(
"name"
)
# => true
Or objects
Let’s say we have @recent_joined variable in the UsersController#index
def index @users = User.paginate :page => params[:page], :order => 'created_at DESC' @recents_joined = User.find( :all, :order =>'created_at DESC', :limit => 2) unless fragment_exist? :recents_joined respond_to do |format| format.html #default index.html format.xml { render :xml => @users } end end
Rails.cache.read(‘views/recent_joined’)
Then in the memcached server memcached -vv
We can see that when the key exists, Rails.cached.read() and Rails.cached.exist?() are doing a get of the key and sending it back. When Rails.cache.delete(), the server is confirming the deletion of the key.
When it doesn’t exist it ends.
Some additional points to keep in mind:
- Expire at
def self.recent Rails.cache.fetch("recent_posts", :expires_in => 30.minutes) do self.find(:all, :limit => 10) end end
Run this query every 30 minutes…
- You don’t need to have memcached installed to develop locally.
You will get MemCacheError (No connection to server): No connection to server Cache miss:
But, your app will work just fine. Rails will always execute the contents of the fetch blocks, and will return nil for any reads.