A basic implementation of response caching in camping.
Camping.goes :MyCampingApp
module MyCampingApp
module Controller
class View < R '/'
def get
cache('root') do
'Expensive operation!'
end
end
end
end
def flush(id)
f = File.dirname(__FILE__) + "/cache/#{id}"
File.delete(f) if File.exists?(f)
end
def cache(id, timeout = 1.hour)
f = File.dirname(__FILE__) + "/cache/#{id}"
if File.exists?(f) && (Time.now - File.stat(f).mtime) < timeout
File.read(f)
else
r = yield
open(f, 'w'){|wr| wr.write(r)}
r
end
end
def self.create
cache_dir = File.dirname(__FILE__) + "/cache"
Dir.mkdir(cache_dir) unless File.directory?(cache_dir)
end
end