Module: FileCache
- Defined in:
- lib/rbbt/util/filecache.rb
Overview
Provides caching functionality for files downloaded from the internet
Constant Summary collapse
- CACHEDIR =
"/tmp/rbbt_cache"
Class Method Summary collapse
- .add(filename, content) ⇒ Object
- .cache_online_elements(ids, pattern = nil, &block) ⇒ Object
- .cachedir ⇒ Object
- .cachedir=(cachedir) ⇒ Object
- .del(filename) ⇒ Object
- .found(filename) ⇒ Object
- .get(filename) ⇒ Object
- .path(filename) ⇒ Object
Class Method Details
.add(filename, content) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/rbbt/util/filecache.rb', line 29 def self.add(filename, content) path = path(filename) FileUtils.makedirs(File.dirname(path), :mode => 0777) Misc.sensiblewrite(path, content) FileUtils.chmod 0666, path path end |
.cache_online_elements(ids, pattern = nil, &block) ⇒ Object
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/rbbt/util/filecache.rb', line 59 def self.cache_online_elements(ids, pattern = nil, &block) ids = [ids] unless Array === ids result_files = {} missing = [] ids.each do |id| filename = pattern ? pattern.sub("{ID}", id.to_s) : id.to_s if FileCache.found(filename) result_files[id] = FileCache.path(filename) else missing << id end end yield(missing).each do |id, content| filename = pattern ? pattern.sub("{ID}", id.to_s) : id.to_s path = FileCache.path(filename) Open.write(path, content) result_files[id] = path end if missing.any? result_files end |
.cachedir ⇒ Object
14 15 16 |
# File 'lib/rbbt/util/filecache.rb', line 14 def self.cachedir CACHEDIR end |
.cachedir=(cachedir) ⇒ Object
9 10 11 12 |
# File 'lib/rbbt/util/filecache.rb', line 9 def self.cachedir=(cachedir) CACHEDIR.replace cachedir FileUtils.mkdir_p CACHEDIR unless File.exist? CACHEDIR end |
.del(filename) ⇒ Object
53 54 55 56 57 |
# File 'lib/rbbt/util/filecache.rb', line 53 def self.del(filename) path = path(filename) FileUtils.rm path if File.exist? path end |
.found(filename) ⇒ Object
41 42 43 |
# File 'lib/rbbt/util/filecache.rb', line 41 def self.found(filename) File.exists? FileCache.path(filename) end |
.get(filename) ⇒ Object
45 46 47 48 49 50 51 |
# File 'lib/rbbt/util/filecache.rb', line 45 def self.get(filename) path = path(filename) return nil if ! File.exists? path File.open(path) end |
.path(filename) ⇒ Object
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/rbbt/util/filecache.rb', line 18 def self.path(filename) filename = File.basename filename filename.match(/(.+)\.(.+)/) base = filename.sub(/\..+/,'') dirs = base.scan(/./).reverse.values_at(0,1,2,3,4).compact File.join(File.join(CACHEDIR, *dirs), filename) end |