Skip to content

Instantly share code, notes, and snippets.

@lesleh
Last active May 1, 2020 15:59
Show Gist options
  • Select an option

  • Save lesleh/a21c18f06ebe5e076ee4 to your computer and use it in GitHub Desktop.

Select an option

Save lesleh/a21c18f06ebe5e076ee4 to your computer and use it in GitHub Desktop.
Ruby in-memory cache.
require 'date'
class Cache
Entry = Struct.new(:expiry, :value)
def initialize(opts={})
@data = Hash.new
@opts = opts
end
def keys
@data.keys
end
def get(key)
@data[key][:value] if has(key)
end
def has(key)
@data.has_key? key
end
def put(key, value, ttl=nil)
ttl ||= @opts[:ttl]
@data[key] = Entry.new(DateTime.new + Rational(ttl, 1440), value)
end
def delete(key)
@data.delete key
end
def clear
@data = Hash.new
end
def invalidate
now = DateTime.new
@data.delete_if {|k, v| v[:expiry] < now}
end
end
@ahyield
Copy link
Copy Markdown

ahyield commented Jul 9, 2018

ttl is in seconds/minutes or days ?

@ivandenysov
Copy link
Copy Markdown

minutes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment