Skip to content

Instantly share code, notes, and snippets.

@teeparham
Created June 3, 2011 03:45
Show Gist options
  • Save teeparham/1005835 to your computer and use it in GitHub Desktop.
Save teeparham/1005835 to your computer and use it in GitHub Desktop.
Rails object caching helpers for ActiveRecord & ActionController
module Rails
class << self
# retrieve keyed item from cache
# store block results if not in cache
#
# usage:
# cash('user-first-10') { User.limit(10) }
def cash(key, options=nil)
object = cache.read(key)
unless object
object = yield
object = object.to_a if object.is_a?(ActiveRecord::Relation)
cache.write(key, object, options)
end
object
end
end
end
class ActiveRecord::Base
def cash(key, options=nil, &block)
Rails.cash(key, options, &block)
end
end
class ActionController::Base
def cash(key, options=nil, &block)
Rails.cash(key, options, &block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment