Skip to content

Instantly share code, notes, and snippets.

@nickel
Created June 9, 2009 05:47
Show Gist options
  • Save nickel/126298 to your computer and use it in GitHub Desktop.
Save nickel/126298 to your computer and use it in GitHub Desktop.
module SimpleCachingTTL
CACHETIME = 24 * 3600 # Once per day
def cache(text, path)
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') { |f| f.write( text ) }
text
end
def set_and_get_cache(page, render = 'erb')
uri = request.env["REQUEST_URI"] == "/" ? 'index' : request.env["REQUEST_URI"]
path = File.join(File.dirname(__FILE__), 'cache', "#{uri}.html")
if File.exists?(path) && ttl?(path)
File.open(path)
else
cache(send(render, page), path)
end
end
def ttl?(path)
File.mtime(path) + CACHETIME > Time.now
end
end
Sinatra::Default.send :include, SimpleCachingTTL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment