class Client
Public Class Methods
new(url = ENV['REPLIT_DB_URL'])
click to toggle source
Change url
to point to a different path. @param url [String, nil]
# File lib/repldb.rb, line 9 def initialize(url = ENV['REPLIT_DB_URL']) @url = url end
Public Instance Methods
del(key)
click to toggle source
Deletes key
. @param key [String]
# File lib/repldb.rb, line 46 def del(key) uri = URI.parse("#{@url}/#{serialize(key)}") req = Net::HTTP::Delete.new(uri.path) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.request(req) end
del_all()
click to toggle source
Deletes all keys, ultimately emptying the database.
# File lib/repldb.rb, line 56 def del_all keys.each { |k| del(k) } end
exists?(key)
click to toggle source
Check if key
exists. @param key [String]
# File lib/repldb.rb, line 81 def exists?(key) !get(key).nil? end
get(key, default = nil)
click to toggle source
Gets key
. If it doesn't exist, <tt>default<tt> will be used. @param key [String] the key to get @param default [Any] the default value if the key doesn't exist.
# File lib/repldb.rb, line 24 def get(key, default = nil) val = get_url("#{@url}/#{serialize(key)}") if val.body == '' default else begin JSON.parse(val.body) rescue StandardError default end end end
get_hash()
click to toggle source
Gets all the keys as a hash.
# File lib/repldb.rb, line 72 def get_hash o = {} ks = keys ks.each { |k| o[k] = get(k) } o end
keys(prefix = '')
click to toggle source
Get all the keys as an array. prefix
can be used to get all keys with a prefix. @param prefix [String, nil] Get all keys with prefix
at the start.
# File lib/repldb.rb, line 40 def keys(prefix = '') get_url("#{@url}?prefix=#{prefix}").body.split("\n").map { |k| deserialize(k) } end
set(key, val)
click to toggle source
Sets key
to val
. @param key [String] the key to set. @param val [Any] the value.
# File lib/repldb.rb, line 16 def set(key, val) post_url(@url.to_s, serialize(key) => JSON.generate(val)) end
set_hash(hash)
click to toggle source
This will append hash
. **This will NOT replace existing keys!** @param hash [Hash]
# File lib/repldb.rb, line 63 def set_hash(hash) if hash.is_a? Hash hash.each { |k, v| set(k, v) } else raise '[GemDb] Error: Argument must be a hash' end end
Private Instance Methods
deserialize(key)
click to toggle source
# File lib/repldb.rb, line 98 def deserialize(key) CGI.unescape key.to_s end
get_url(url)
click to toggle source
# File lib/repldb.rb, line 90 def get_url(url) Net::HTTP.get_response(URI(url)) end
post_url(url, data)
click to toggle source
internals
# File lib/repldb.rb, line 86 def post_url(url, data) Net::HTTP.post_form(URI(url), data) end
serialize(key)
click to toggle source
# File lib/repldb.rb, line 94 def serialize(key) CGI.escape key.to_s end