Assuming your want to use Memcached as caching layer, you might probably be happy to know that the Rails caching architecture already supports Memcached storage.
Just configure it in your application.rb
file (assuming you are using Rails 3):
module MyApp
class Application < Rails::Application
config.cache_store = :dalli_store
end
end
Here I'm using the :dalli_store
which is provided by the Dalli gem, an high performance Memcached client. Rails ships with a standard :memcached
store, so you can use it if you want.
Then, once configured, you can access your cache layer using Rails.cache
.
Rails.cache.write
Rails.cache.read
Rails.cache.fetch
Rails.cache.delete
For instance, let's say you want to cache an expensive ActiveRecord query.
class Post < ActiveRecord::Base
def expensive_query
Rails.cache.fetch("posts/expensive_query") do
where("1 = 1").all
end
end
end
The first time, when the cache is not available, #fetch
will execute the content of the block and cache it. Later, the cache will simply be returned.