Sha256: 0e38859b205e3e3128ac2a336edd84dc4faa1cfdbfbcddfea3690a69070b1cbb

Contents?: true

Size: 1.26 KB

Versions: 8

Compression:

Stored size: 1.26 KB

Contents

require "fileutils"

class Geminabox::DiskCache
  attr_reader :root_path

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

  def flush_key(key)
    path = path(key_hash(key))
    FileUtils.rm_f(path)
  end

  def flush
    FileUtils.rm_rf(root_path)
    ensure_dir_exists!
  end

  def cache(key)
    key_hash = key_hash(key)
    read(key_hash) || write(key_hash, yield)
  end

  def marshal_cache(key)
    key_hash = key_hash(key)
    marshal_read(key_hash) || marshal_write(key_hash, yield)
  end

protected

  def ensure_dir_exists!
    FileUtils.mkdir_p(root_path)
  end

  def key_hash(key)
    Digest::MD5.hexdigest(key)
  end

  def path(key_hash)
    File.join(root_path, key_hash)
  end

  def read(key_hash)
    read_int(key_hash) { |path| File.read(path) }
  end

  def marshal_read(key_hash)
    read_int(key_hash) { |path| Marshal.load(File.open(path)) }
  end

  def read_int(key_hash)
    path = path(key_hash)
    yield(path) if File.exists?(path)
  end

  def write(key_hash, value)
    write_int(key_hash) { |f| f << value }
    value
  end

  def marshal_write(key_hash, value)
    write_int(key_hash) { |f| Marshal.dump(value, f) }
    value
  end

  def write_int(key_hash)
    File.open(path(key_hash), 'wb') { |f| yield(f) }
  end

end

Version data entries

8 entries across 8 versions & 3 rubygems

Version Path
geminabox-0.11.1 lib/geminabox/disk_cache.rb
geminabox-inflection-0.12.0 lib/geminabox/disk_cache.rb
geminabox-inflection-0.11.0 lib/geminabox/disk_cache.rb
geminabox-0.11.0 lib/geminabox/disk_cache.rb
geminabox-bootstrap-0.10.3 lib/geminabox/disk_cache.rb
geminabox-0.10.1 lib/geminabox/disk_cache.rb
geminabox-0.10.0 lib/geminabox/disk_cache.rb
geminabox-0.9.0 lib/geminabox/disk_cache.rb