Skip to content

Instantly share code, notes, and snippets.

@tanema
Last active May 26, 2021 18:22
Show Gist options
  • Save tanema/b9ce5688d4d45441813602f95df7f0fb to your computer and use it in GitHub Desktop.
Save tanema/b9ce5688d4d45441813602f95df7f0fb to your computer and use it in GitHub Desktop.
Create a local key value store using only the standard library in ruby
require 'localstore'
DB.set(key: "value")
DB.exists?(:key) # => true
DB.get(:key) # => "value"
DB.get(:other, "default value") # => default val
DB.get(:other) do
val = computed_val()
DB.set(other: val)
val
end
# => value of val in block
DB.keys # => [:key, :other]
DB.del(:key)
DB.clear()
require "pstore"
require "forwardable"
class DB
extend SingleForwardable
def_delegators :new, :keys, :exists?, :set, :get, :del, :clear
attr_reader :db
def initialize(path: ".db.pstore")
@db = PStore.new(path)
end
def keys
db.transaction(true) { db.roots }
end
def exists?(key)
db.transaction(true) { db.root?(key) }
end
def set(**args)
db.transaction do
args.each {|key, val| val.nil? ? db.delete(key) : db[key] = val}
end
end
def get(key, default=nil)
val = db.transaction(true) { db[key] }
return val unless val.nil?
return default unless default.nil?
return yield if block_given?
nil
end
def del(*args)
db.transaction { args.each { |key| db.delete(key) } }
end
def clear
del(*keys)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment