Project

redrecord

0.0
No commit activity in last 3 years
No release in over 3 years
Redis cacheing for ActiveRecord
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

active_support
>= 0

Runtime

>= 0
 Project Readme
redrecord
---------

This gem pre-caches your ActiveRecord model's calculated attributes (computed
fields) in Redis.


Example
-------

 class User < ActiveRecord::Base

   redis_cache do
     def fullname
       firstname + ' ' + lastname
     end
   end

 end


Methods defined inside the "cache" block are redefined to get the answer
from redis first.  The cached attributes are saved whenever the record is
saved, in an after_commit callback.


Cache invalidation for associations
-----------------------------------

Redrecord can be used to cache attributes that use assocations:

 class User < ActiveRecord::Base
   has_many :preferences

   redis_cache do
     def preferences_list
       preferences.map(&:name).join(', ')
     end
   end

 end

 class Preference < ActiveRecord::Base
   belongs_to :user

   invalidate_cache_on :user

 end


In this example, whenever a preference is saved, the associated user record
will be recalculated and saved in redis.  If it is an array (eg. has_many)
then all of the associated records will be re-cached.

Other instance methods of interest:

 obj.remove_from_cache! # Remove redis cache for an object.
 obj.add_to_cache!      # Recalculate fields and store in redis.
 obj.cached_fields      # hash of the cached fields and their values
 obj.attribs_with_cached_fields # cached_fields merged with AR attributes
 obj.verify_cache!      # raise an error if cache doesn't match calculated


If redis is down?
-----------------

To enable talking to a redis server, set Redrecord.enabled=true

If Redrecord can't access redis within a timeout (Redrecord.timeout=15 by
default) then it sets enabled=false, disabling all redis access so your
application can keep working without the cache.

For testing purposes, you can set Redrecord.write_only = true
This keeps the cache contents up to date but does not read back any cached
content.


Setup
-----

in your Gemfile:

   gem 'redrecord'

in your rails app config/initializers/redrecord.rb:

   $redis = Redis.new(:host => 'localhost', :port => 6379, :db => 1)
   Redrecord.redis = $redis
   Redrecord.enabled = true



Contact the author
------------------

Andrew Snow <andrew@modulus.org>
Andys^ on irc.freenode.net