Module: DiskCache
- Extended by:
- DiskCache
- Included in:
- DiskCache
- Defined in:
- lib/disk_cache.rb,
lib/disk_cache/version.rb
Constant Summary collapse
- VERSION =
"0.0.8"
Instance Method Summary collapse
-
#clear! ⇒ Object
Public: this removes all contents of the cache.
-
#del(url) ⇒ Object
Public: delete a file from the cache.
-
#filepath(url) ⇒ Object
Public: calculate the path/filename of a file’s URL.
-
#get(url) ⇒ Object
Public: get a file from the cache.
-
#pget(url) ⇒ Object
Public: get a file and save it to the cache if it isn’t there already.
-
#put(url) ⇒ Object
Public: save a file to the cache.
Instance Method Details
#clear! ⇒ Object
Public: this removes all contents of the cache.
109 110 111 112 113 114 115 |
# File 'lib/disk_cache.rb', line 109 def clear! if File.exists? cache_dir Dir.glob(cache_dir + '*').each do |f| FileUtils.rm_r f end end end |
#del(url) ⇒ Object
Public: delete a file from the cache
url - The URL to the file
Example:
DiskCache.del('http://example.com/test123.jpg')
# => nil
Returns nil
89 90 91 |
# File 'lib/disk_cache.rb', line 89 def del(url) FileUtils.rm filepath(url), force: true end |
#filepath(url) ⇒ Object
Public: calculate the path/filename of a file’s URL
url - the URL of the file
Example:
DiskCache.filepath('http://example.com/test123.jpg')
# => "cache/9a/e2/74d94c34542ddd1b64667c1d4e392211ff67"
Returns a Sting with the full path and filename
103 104 105 106 |
# File 'lib/disk_cache.rb', line 103 def filepath(url) hsh = hash url path_h(hsh) + filename_h(hsh) end |
#get(url) ⇒ Object
Public: get a file from the cache
url - The URL to the file
Examples:
DiskCache.get('http://example.com/test123.jpg')
# => #<File:9ae274d94c34542ddd1b64667c1d4e392211ff67>
DiskCache.get('http://example.com/test123.jpg')
# => nil
Returns the File or nil
58 59 60 61 62 |
# File 'lib/disk_cache.rb', line 58 def get(url) File.open(filepath(url), "rb") rescue Errno::ENOENT nil end |
#pget(url) ⇒ Object
Public: get a file and save it to the cache if it isn’t there already
url - The URL to the file
Examples:
DiskCache.get('http://example.com/test123.jpg')
# => #<File:9ae274d94c34542ddd1b64667c1d4e392211ff67>
Returns a File
74 75 76 77 |
# File 'lib/disk_cache.rb', line 74 def pget(url) put(url) get(url) end |
#put(url) ⇒ Object
Public: save a file to the cache
url - The URL to the file
Example:
DiskCache.put('http://example.com/test123.jpg')
#=> nil
Returns: nil
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/disk_cache.rb', line 20 def put(url) file = filepath(url) return nil if File.exist?(file) FileUtils.mkdir_p path(url) trys = 0 begin trys = trys + 1 data = open(escape(url)).read File.open(file, "wb") { |f| f << data } rescue OpenURI::HTTPError => httperror raise httperror unless trys < 3 retry rescue Timeout::Error => timeout raise timeout unless trys < 3 retry rescue OpenSSL::SSL::SSLError => ssl raise ssl unless trys < 3 retry rescue => error raise error end nil end |