@yorzi

All about Ruby/Rails/Javascript/CoffeeScript/iOS/Ubuntu

Fork me on GitHub

Dalli on Rails3

Today I tried a new pure Ruby memcahed client in one of my Rails3 projects, it’s named as ”Dalli”. It’s an excellent memcached client as Mike Perham announced in August last year. You can detect more details about it on its code. Dalli is just faster performance than memcache-client and easy to use in Rails3 or on Heroku.

Make sure you’ve installed 1.4+ memcached on your machine, then you can configure Dalli as what you did with memcache-client before: 1. add gem in Gemfile gem 'dalli' 2. Config the underlying cache store as dalli_store in production.rb

Memcached is delaulted on port 11211.

config.cache_store = :dalli_store, 'localhost:11211' 3. Now you will find the Rails.cache class is changed to Rails.cache.class:

Rails.cache.class == ActiveSupport::Cache::DalliStore 4. You can use it easily in you Rails3 application class Food < ActiveRecord::Base after_save :expire_food_caches

def self.all_view_types

  Rails.cache.fetch("food_types") do
      Food.all.map{|s| s.view_type}.uniq
  end

end

protected def expire_food_caches

   unless Food.all_view_types.include?(self.view_type)
       Rails.cache.delete("food_types")
   end

end end Note: Rails.cache.fetch() with a block will return the cached value if it exists, otherwise it will return the value and write cache with the value at the same time.

Resource about Cache: Scaling Rails :
http://railslab.newrelic.com/scaling-rails Caching with Rails :
http://guides.rubyonrails.org/caching_with_rails.html ActiveSupport::Cache::Store :
http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-clear ActiveSupport::Memoizable :
http://ilstar.blogbus.com/logs/84754288.html#cmt

Comments