Last active
March 21, 2021 21:30
-
-
Save kwilczynski/3680388 to your computer and use it in GitHub Desktop.
Simple Cache class in Ruby using pstore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Cache | |
attr_reader :cache | |
class << self | |
def get(file, expiry, &block) | |
raise ArgumentError, 'no block given' unless block_given? | |
Cache.new(file, expiry, &block).cache | |
end | |
end | |
def initialize(file, expiry, &block) | |
require 'pstore' | |
store = PStore.new(file) | |
@cache = begin | |
store.transaction do | |
if Time.now.to_i - (store[:time] ||= 0) >= expiry | |
store[:time] = Time.now.to_i | |
store[:cache] = block.call | |
end | |
store[:cache] | |
end | |
end | |
end | |
end | |
if $0 == __FILE__ | |
c = Cache.get('/tmp/test.pstore', 10) do | |
sleep 5 | |
Time.new.to_s | |
end | |
p c | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment