Class: Rhcf::Utils::DownloadCache

Inherits:
Object
  • Object
show all
Includes:
FileUtils
Defined in:
lib/rhcf/utils/download_cache.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache_id = 'default', ttl = nil, root_path = nil) ⇒ DownloadCache

Returns a new instance of DownloadCache.



10
11
12
13
14
# File 'lib/rhcf/utils/download_cache.rb', line 10

def initialize(cache_id= 'default', ttl = nil, root_path = nil)
  @cache_id = cache_id
  @ttl = ttl
  @root_path ||= "/tmp/#{self.class.name}"
end

Class Method Details

.hit_fname?(fname, ttl) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rhcf/utils/download_cache.rb', line 42

def self.hit_fname?(fname, ttl)
  
  if File.exist?(fname) 
    if ttl
      File::Stat.new(fname).ctime > Time.now - ttl
    else 
      true
    end
  else
    false
  end
end

Instance Method Details

#download!(url, outfile) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/rhcf/utils/download_cache.rb', line 27

def download!(url, outfile)
  mkdir_p(File.dirname(outfile))
  File.open(outfile, 'w') do |fd|
    open(url, "r") do |down|
      fd.write(down.read)
    end
  end
  outfile
end

#filename_for(url) ⇒ Object



55
56
57
58
59
60
# File 'lib/rhcf/utils/download_cache.rb', line 55

def filename_for(url)
  hash =  Digest::MD5.hexdigest(url)
  uri = URI(url)
  basename = File.basename(uri.path)
  File.join(@root_path, @cache_id, hash, basename) 
end

#get(url) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/rhcf/utils/download_cache.rb', line 17

def get(url)
  outfile = filename_for(url)
  return outfile if self.class.hit_fname?(outfile, @ttl) # here goes the cache
  download!(url, outfile)
rescue 
  File.unkink(outfile) if File.exist?(outfile)
  raise
end

#hit?(url) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
# File 'lib/rhcf/utils/download_cache.rb', line 37

def hit?(url)
  outfile = filename_for(url)
  self.class.hit_fname?(outfile, @ttl) # here goes the cache
end