Skip to content

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

License

Notifications You must be signed in to change notification settings

arydjmal/model_cached

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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
    @_current_account ||= Account.find_by_subdomain(request.subdomain)
  end

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

  def require_account
    unless current_account
      redirect_to sign_up_url
    end
  end

  def require_user
    unless current_account
      redirect_to sign_in_url
    end
  end
end

Dependencies

memcached

Install

In your Gemfile:

gem 'model_cached'

Copyright © 2012 Ary Djmal, released under the MIT license

About

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

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages