Class: CacheFetcher

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

Instance Method Summary collapse

Constructor Details

#initialize(cache_dir = File.expand_path(File.dirname(__FILE__)) + '/tmp') ⇒ CacheFetcher

Returns a new instance of CacheFetcher.



6
7
8
9
# File 'lib/cache_fetcher.rb', line 6

def initialize(cache_dir=File.expand_path(File.dirname(__FILE__)) + '/tmp')
   # this is the dir where we store our cache
   @cache_dir = cache_dir
end

Instance Method Details

#fetch(url) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/cache_fetcher.rb', line 12

def fetch(url)
   file = MD5.hexdigest(url)
   file_path = File.join("", @cache_dir, file)
   # we check if the file -- a MD5 hexdigest of the URL -- exists
   #  in the dir. If it does we just read data from the file and return
   if !File.exists? file_path
     #puts 'Not found in cache'
     # if the file does not exist (or if the data is not fresh), we
     #  make an HTTP request and save it to a file
     #puts 'Fetching file from internet...'
     File.open(file_path, "w") do |data|
        data << Net::HTTP.get_response(URI.parse(url)).body
     end
   else
     #puts 'Using cache'
   end
   return File.new(file_path)
end