Class: CachedHttpFile

Inherits:
Object
  • Object
show all
Defined in:
lib/tiny_site.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, expires_in = 3600) ⇒ CachedHttpFile

Returns a new instance of CachedHttpFile.



32
33
34
# File 'lib/tiny_site.rb', line 32

def initialize(url, expires_in=3600)
  @url, @expires_in = url, expires_in
end

Class Method Details

.bustObject



69
70
71
72
# File 'lib/tiny_site.rb', line 69

def bust
  puts 'busting cache'
  @files = {}
end

.filesObject



63
64
65
# File 'lib/tiny_site.rb', line 63

def files
  @files ||= {}
end

.get(url, expires_in = 3600) ⇒ Object



66
67
68
# File 'lib/tiny_site.rb', line 66

def get(url, expires_in=3600)
  (new url, expires_in).get
end

Instance Method Details

#cachedObject



49
50
51
# File 'lib/tiny_site.rb', line 49

def cached
  return 200, self.class.files[@url][:content]
end

#cached?Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/tiny_site.rb', line 46

def cached?
  self.class.files[@url] && self.class.files[@url][:expires_at] > Time.now
end

#fetchObject



36
37
38
39
40
41
42
43
44
# File 'lib/tiny_site.rb', line 36

def fetch
  puts "fetching #{@url}"
  @body = open(@url).read
  store
  return 200, @body
rescue OpenURI::HTTPError => error
  puts "OpenURI::HTTPError: #{error.message}"
  return error.message.to_i, nil
end

#getObject



58
59
60
# File 'lib/tiny_site.rb', line 58

def get
  (cached? && cached) || fetch
end

#storeObject



53
54
55
56
# File 'lib/tiny_site.rb', line 53

def store
  puts "storing body of #{@url}"
  self.class.files[@url] = {:content => @body, :expires_at => Time.now + @expires_in}
end