Sha256: 1e6a98ddb6fd8059fd8854bf782c0bf18b0f32e2268ebd05d7ed49d91d49728e

Contents?: true

Size: 794 Bytes

Versions: 2

Compression:

Stored size: 794 Bytes

Contents

require 'yaml'

module LitmusPaper
  class Cache
    def initialize(location, namespace, ttl)
      @path = File.join(location, namespace)
      @ttl = ttl

      FileUtils.mkdir_p(@path)
    end

    def set(key, value)
      return unless @ttl > 0
      File.open(File.join(@path, key), "a") do |f|
        f.flock(File::LOCK_EX)
        f.rewind
        f.write("#{Time.now.to_f + @ttl} #{YAML::dump(value)}")
        f.flush
        f.truncate(f.pos)
      end
    end

    def get(key)
      return unless File.exists?(File.join(@path, key))
      File.open(File.join(@path, key), "r") do |f|
        f.flock(File::LOCK_SH)
        entry = f.read
        expires_at, value = entry.split(" ", 2)
        expires_at.to_f < Time.now.to_f ? nil : YAML::load(value)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
litmus_paper-1.1.1 lib/litmus_paper/cache.rb
litmus_paper-1.1.0 lib/litmus_paper/cache.rb