Skip to content

Instantly share code, notes, and snippets.

@yule
Created August 31, 2011 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yule/1183415 to your computer and use it in GitHub Desktop.
Save yule/1183415 to your computer and use it in GitHub Desktop.
key/value store for CodeBrawl

#Sloth

Sloth is a very lazy, slow key value store. It was created for Code Brawl. Its extremely simple and essentially uses files for storage.

You can do get, set and delete and also retreive a list of keys.

require 'sloth' db = Sloth.new('db_name')

##set db.set('foo',"honkey") db.set('bar','tonk')

##get puts db.get('foo') => 'honkey'

##delete db.delete('foo')

##list keys puts db.keys => ['bar']

class Sloth;attr_accessor :d;def initialize(d);@d=d;Dir.mkdir(d) unless File.directory?(d);end;def set(k,v);l=f(k,"w");l.puts v;end;def get(k);return unless exists?(k);l=f(k,"rb");l.read;end;def delete(k);return unless exists?(k);File.delete("#{@d}/#{k}.slo");end;def keys;Dir.entries(@d).map{|x|x[0..-5]};end;def exists?(k);File.exists? "#{@d}/#{k}.slo";end;def f(k,m);File.open("#{@d}/#{k}.slo",m);end;end
class Sloth
attr_accessor :db
def initialize(db)
@db = db
Dir.mkdir(db) unless File.directory?(db)
end
def set(key, value)
file = f(key, "w")
file.puts value
file.close
end
def get(key)
return unless exists?(key)
file = f(key, "rb")
return file.read
end
def delete(key)
return unless exists?(key)
File.delete("#{@db}/#{key}.slo")
end
def keys
Dir.entries(@db).map {|x| x[0..-5]}
end
private
def exists?(key)
File.exists? "#{@db}/#{key}.slo"
end
def f(key, mode)
File.open("#{@db}/#{key}.slo", mode)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment