Class: HTTPCache

Inherits:
Object
  • Object
show all
Defined in:
lib/wonko_the_sane/util/http_cache.rb

Overview

www.ericson.net/content/2011/04/caching-http-requests-with-ruby/ TODO proper etags and other caching stuff

Constant Summary collapse

@@defaultCatcher =
HTTPCache.new 'cache/network'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(basedir) ⇒ HTTPCache

Returns a new instance of HTTPCache.



4
5
6
7
8
9
# File 'lib/wonko_the_sane/util/http_cache.rb', line 4

def initialize(basedir)
  @basedir = basedir
  FileUtils.mkdir_p @basedir unless Dir.exist? @basedir
  @etags = {}
  @etags = JSON.parse File.read(@basedir + '/etags.json') if File.exists? @basedir + '/etags.json'
end

Class Method Details

.file(url, options = {}) ⇒ Object



140
141
142
# File 'lib/wonko_the_sane/util/http_cache.rb', line 140

def self.file(url, options = {})
  @@defaultCatcher.file(options[:ctxt] || 'Download', url, (options.key?(:key) ? options[:key] : url), options[:check_stale] || false)
end

.get(url, options = {}) ⇒ Object



137
138
139
# File 'lib/wonko_the_sane/util/http_cache.rb', line 137

def self.get(url, options = {})
  @@defaultCatcher.get(options[:ctxt] || 'Download', url, (options.key?(:key) ? options[:key] : url), options[:check_stale] || false)
end

Instance Method Details

#file(ctxt, url, key, check_stale = true) ⇒ Object



17
18
19
20
# File 'lib/wonko_the_sane/util/http_cache.rb', line 17

def file(ctxt, url, key, check_stale = true)
  fetch ctxt, url, key, check_stale
  File.open @basedir + '/' + key, 'r'
end

#get(ctxt, url, key, check_stale = true) ⇒ Object

HTTP GETs a url if it doesn’t exist locally



12
13
14
15
# File 'lib/wonko_the_sane/util/http_cache.rb', line 12

def get(ctxt, url, key, check_stale = true)
  fetch ctxt, url, key, check_stale
  IO.read @basedir + '/' + key
end