Class: TRuby::FileCache
- Inherits:
-
Object
- Object
- TRuby::FileCache
- Defined in:
- lib/t_ruby/cache.rb
Overview
File-based persistent cache
Instance Attribute Summary collapse
-
#cache_dir ⇒ Object
readonly
Returns the value of attribute cache_dir.
-
#max_age ⇒ Object
readonly
Returns the value of attribute max_age.
Instance Method Summary collapse
- #clear ⇒ Object
- #delete(key) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(cache_dir: ".t-ruby-cache", max_age: 3600) ⇒ FileCache
constructor
A new instance of FileCache.
- #prune ⇒ Object
- #set(key, value) ⇒ Object
Constructor Details
#initialize(cache_dir: ".t-ruby-cache", max_age: 3600) ⇒ FileCache
Returns a new instance of FileCache.
133 134 135 136 137 |
# File 'lib/t_ruby/cache.rb', line 133 def initialize(cache_dir: ".t-ruby-cache", max_age: 3600) @cache_dir = cache_dir @max_age = max_age FileUtils.mkdir_p(@cache_dir) end |
Instance Attribute Details
#cache_dir ⇒ Object (readonly)
Returns the value of attribute cache_dir.
131 132 133 |
# File 'lib/t_ruby/cache.rb', line 131 def cache_dir @cache_dir end |
#max_age ⇒ Object (readonly)
Returns the value of attribute max_age.
131 132 133 |
# File 'lib/t_ruby/cache.rb', line 131 def max_age @max_age end |
Instance Method Details
#clear ⇒ Object
167 168 169 170 |
# File 'lib/t_ruby/cache.rb', line 167 def clear FileUtils.rm_rf(@cache_dir) FileUtils.mkdir_p(@cache_dir) end |
#delete(key) ⇒ Object
162 163 164 165 |
# File 'lib/t_ruby/cache.rb', line 162 def delete(key) path = cache_path(key) FileUtils.rm_f(path) end |
#get(key) ⇒ Object
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
# File 'lib/t_ruby/cache.rb', line 139 def get(key) path = cache_path(key) return nil unless File.exist?(path) # Check if stale if File.mtime(path) < Time.now - @max_age File.delete(path) return nil end data = File.read(path) JSON.parse(data, symbolize_names: true) rescue JSON::ParserError File.delete(path) nil end |
#prune ⇒ Object
172 173 174 175 176 |
# File 'lib/t_ruby/cache.rb', line 172 def prune Dir.glob(File.join(@cache_dir, "*.json")).each do |path| File.delete(path) if File.mtime(path) < Time.now - @max_age end end |
#set(key, value) ⇒ Object
156 157 158 159 160 |
# File 'lib/t_ruby/cache.rb', line 156 def set(key, value) path = cache_path(key) File.write(path, JSON.generate(value)) value end |