Class: Gemstar::Cache
- Inherits:
-
Object
- Object
- Gemstar::Cache
- Defined in:
- lib/gemstar/cache.rb
Constant Summary collapse
- MAX_CACHE_AGE =
1 day
60 * 60 * 24
- CACHE_DIR =
File.join(Gemstar::Config.home_directory, "cache")
- @@initialized =
false
Class Method Summary collapse
- .fetch(key, force: false, &block) ⇒ Object
- .flush! ⇒ Object
- .flush_directory(directory) ⇒ Object
- .fresh?(path) ⇒ Boolean
- .init ⇒ Object
- .path_for(key) ⇒ Object
- .peek(key) ⇒ Object
Class Method Details
.fetch(key, force: false, &block) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/gemstar/cache.rb', line 19 def self.fetch(key, force: false, &block) init path = path_for(key) if !force && fresh?(path) content = File.read(path) return nil if content == "__404__" return content end begin data = block.call File.write(path, data || "__404__") data rescue File.write(path, "__404__") nil end end |
.flush! ⇒ Object
62 63 64 65 66 |
# File 'lib/gemstar/cache.rb', line 62 def self.flush! init flush_directory(CACHE_DIR) end |
.flush_directory(directory) ⇒ Object
68 69 70 71 72 73 74 75 76 77 |
# File 'lib/gemstar/cache.rb', line 68 def self.flush_directory(directory) return 0 unless Dir.exist?(directory) entries = Dir.children(directory) entries.each do |entry| FileUtils.rm_rf(File.join(directory, entry)) end entries.count end |
.fresh?(path) ⇒ Boolean
56 57 58 59 60 |
# File 'lib/gemstar/cache.rb', line 56 def self.fresh?(path) return false unless File.exist?(path) (Time.now - File.mtime(path)) <= MAX_CACHE_AGE end |
.init ⇒ Object
12 13 14 15 16 17 |
# File 'lib/gemstar/cache.rb', line 12 def self.init return if @@initialized FileUtils.mkdir_p(CACHE_DIR) @@initialized = true end |
.path_for(key) ⇒ Object
52 53 54 |
# File 'lib/gemstar/cache.rb', line 52 def self.path_for(key) File.join(CACHE_DIR, Digest::SHA256.hexdigest(key)) end |
.peek(key) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/gemstar/cache.rb', line 40 def self.peek(key) init path = path_for(key) return nil unless fresh?(path) content = File.read(path) return nil if content == "__404__" content end |