Created
June 3, 2011 03:45
-
-
Save teeparham/1005835 to your computer and use it in GitHub Desktop.
Rails object caching helpers for ActiveRecord & ActionController
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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