Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 40 lines (31 sloc) 0.64 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
require "fileutils"

class Geminabox::DiskCache
  attr_reader :root_path

  def initialize(root_path)
    @root_path = root_path
    ensure_dir_exists!
  end

  def flush
    FileUtils.rm_rf(root_path)
    ensure_dir_exists!
  end

  def cache(key)
    key = Digest::MD5.hexdigest(key)
    read(key) || write(key, yield)
  end

  def read(key)
    path = File.join(root_path, key)
    File.read(path) if File.exists?(path)
  end

  def write(key, value)
    path = File.join(root_path, key)
    File.open(path, 'wb'){|f|
      f << value
    }
    value
  end

protected

  def ensure_dir_exists!
    FileUtils.mkdir_p(root_path)
  end
end
Something went wrong with that request. Please try again.