Class: TRuby::FileCache

Inherits:
Object
  • Object
show all
Defined in:
lib/t_ruby/cache.rb

Overview

File-based persistent cache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache_dir: ".t-ruby-cache", max_age: 3600) ⇒ FileCache

Returns a new instance of FileCache.



132
133
134
135
136
# File 'lib/t_ruby/cache.rb', line 132

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_dirObject (readonly)

Returns the value of attribute cache_dir.



130
131
132
# File 'lib/t_ruby/cache.rb', line 130

def cache_dir
  @cache_dir
end

#max_ageObject (readonly)

Returns the value of attribute max_age.



130
131
132
# File 'lib/t_ruby/cache.rb', line 130

def max_age
  @max_age
end

Instance Method Details

#clearObject



166
167
168
169
# File 'lib/t_ruby/cache.rb', line 166

def clear
  FileUtils.rm_rf(@cache_dir)
  FileUtils.mkdir_p(@cache_dir)
end

#delete(key) ⇒ Object



161
162
163
164
# File 'lib/t_ruby/cache.rb', line 161

def delete(key)
  path = cache_path(key)
  File.delete(path) if File.exist?(path)
end

#get(key) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/t_ruby/cache.rb', line 138

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

#pruneObject



171
172
173
174
175
# File 'lib/t_ruby/cache.rb', line 171

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



155
156
157
158
159
# File 'lib/t_ruby/cache.rb', line 155

def set(key, value)
  path = cache_path(key)
  File.write(path, JSON.generate(value))
  value
end