class Pa::Cache

Attributes

path[R]

Public Class Methods

new(path) click to toggle source
# File lib/pa/cache.rb, line 7
def initialize(path)
  @path = File.join(path, 'cache')
end

Public Instance Methods

fetch(key, time) { |block))| ... } click to toggle source
# File lib/pa/cache.rb, line 11
def fetch(key, time, &block)
  write(key, (yield block)) if !exists?(key) || expired?(key, time)
  read key
end

Private Instance Methods

exists?(key) click to toggle source
# File lib/pa/cache.rb, line 22
def exists?(key)
  File.exist? file_path(key)
end
expired?(key, time) click to toggle source
# File lib/pa/cache.rb, line 18
def expired?(key, time)
  Time.now.in_time_zone(App.config.timezone) - File.mtime(file_path(key)) > time
end
file_path(key) click to toggle source
# File lib/pa/cache.rb, line 35
def file_path(key)
  File.expand_path File.join(path, key)
end
initialize_path!(path) click to toggle source
# File lib/pa/cache.rb, line 39
def initialize_path!(path)
  return if File.exist?(path)

  FileUtils.mkdir_p File.dirname path
  FileUtils.touch path
end
read(key) click to toggle source
# File lib/pa/cache.rb, line 26
def read(key)
  IO.read file_path(key), mode: 'r'
end
write(key, content) click to toggle source
# File lib/pa/cache.rb, line 30
def write(key, content)
  initialize_path! file_path(key)
  IO.write file_path(key), content
end