model_cached plugin

This Rails 3 gem gives you the ability to transparently cache single active record objects using memcached.

The purpose is to cache by fields that are being validated for unique values.

Cache gets refresh after save, and expire after destroy or after a logical delete.

It is less than 100 lines of code, so don’t be shy to look at the source for full understanding.

NOTE: For rails 2.x use the unmaintained rails2 branch.

Usage

In your model:

# defines find_by_id, and handles the cache refresh or expiration
# also modifies find, so when pass a single integer it uses find_by_id or raises and exception
cache_by :id

# same plus defines find_by_email
cache_by :id, :email

# same but only gives you the cache version if call it with the right scope
# eg: User.find_by_id(1) => will not use cache
# eg: current_account.users.find_by_id(1) => will use cache
cache_by :id, :email, :scope => :account_id

# you should use the :logical_delete option specifying the method that checks if a record is deleted
# disregard if not using logical deletes
cache_by :id, :email, :logical_delete => :is_deleted?

Real life example

class Account < ActiveRecord::Base
  has_many :users
  cache_by :subdomain
end

class User < ActiveRecord::Base
  belongs_to :account
  cache_by :id, :scope => :account_id
end

class ApplicationController < ActionController::Base
  before_filter :require_account, :require_user

  private
  def 
    @_current_account ||= Account.find_by_subdomain(request.subdomain)
  end

  def current_user
    @_current_user ||= session[:user_id] ? .users.find_by_id(session[:user_id]) : nil
  end

  def 
    unless 
      redirect_to 
    end
  end

  def require_user
    unless 
      redirect_to 
    end
  end
end

Dependencies

memcached

Install

In your Gemfile:

gem 'model_cached'

Copyright © 2012 Ary Djmal, released under the MIT license