Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

response caching in camping (See related posts)

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

Comments on this post

zimbatm posts on Mar 12, 2008 at 18:53
Nice example.

I'd change only one thing : Camping handles the return of IO instances. Thus, I would change "File.read(f)" to "File.open(f)" and let the web server handle the read.

You need to create an account or log in to post comments to this site.


Click here to browse all 4863 code snippets

Related Posts