Class: Rhcf::Utils::DownloadCache
- Inherits:
-
Object
- Object
- Rhcf::Utils::DownloadCache
- Includes:
- FileUtils
- Defined in:
- lib/rhcf/utils/download_cache.rb
Class Method Summary collapse
Instance Method Summary collapse
- #download!(url, outfile) ⇒ Object
- #filename_for(url) ⇒ Object
- #get(url) ⇒ Object
- #hash_tree(hash) ⇒ Object
- #hit?(url) ⇒ Boolean
-
#initialize(cache_id = 'default', ttl = nil, root_path = nil) ⇒ DownloadCache
constructor
A new instance of DownloadCache.
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
49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/rhcf/utils/download_cache.rb', line 49 def self.hit_fname?(fname, ttl) if File.exist?(fname) and !File.zero?(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
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/rhcf/utils/download_cache.rb', line 24 def download!(url, outfile) uri = URI(url) expected_file_size = nil Net::HTTP.start(uri.host) do |http| resp = http.get(uri.path) expected_file_size = resp.body.size mkdir_p(File.dirname(outfile)) File.open(outfile, 'wb') do |fd| fd.write(resp.body) end end if expected_file_size != File.size(outfile) raise "Different file size expected: '%d' bytes got: '%d' bytes " % [expected_file_size, File.size(outfile)] end raise "Empty file" if File.zero?(outfile) outfile end |
#filename_for(url) ⇒ Object
62 63 64 65 66 67 |
# File 'lib/rhcf/utils/download_cache.rb', line 62 def filename_for(url) hash = Digest::MD5.hexdigest(url) uri = URI(url) basename = File.basename(uri.path) File.join(@root_path, @cache_id, hash_tree(hash), basename) end |
#get(url) ⇒ Object
17 18 19 20 21 |
# 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) end |
#hash_tree(hash) ⇒ Object
69 70 71 |
# File 'lib/rhcf/utils/download_cache.rb', line 69 def hash_tree(hash) [*(hash[0,3].split('')) ,hash].join('/') end |
#hit?(url) ⇒ Boolean
44 45 46 47 |
# File 'lib/rhcf/utils/download_cache.rb', line 44 def hit?(url) outfile = filename_for(url) self.class.hit_fname?(outfile, @ttl) # here goes the cache end |