Skip to content

Instantly share code, notes, and snippets.

@dirk
Created March 21, 2010 14:12
Show Gist options
  • Save dirk/339321 to your computer and use it in GitHub Desktop.
Save dirk/339321 to your computer and use it in GitHub Desktop.
# 21 Mar. 2010: Pulled from tedb's fork to add cache_and_render method.
class ApplicationController < ActionController::Base
# Other random stuff.
protected
def cache_and_render(key, opts = {})
cached = cache(key, opts)
render :text => cached
return cached
end
def cache(key, opts = {})
cache = read_fragment(key, opts)
if not cache
cache = yield
write_fragment(key, cache, opts)
end
return cache
end
end
class Controller < ApplicationController
def action
# Filtering or other random stuff.
cache('key', :expires_in => 5.minutes) do
"This will be cached and rendered."
end
# This will be cached as well, but stored in cached_data instead of being rendered.
cached_data = cache('other_key', {}, false) { User.first.email }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment