Skip to content

Instantly share code, notes, and snippets.

@razielgn
Created September 2, 2011 22:37
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 razielgn/03ddb0f2557b77135f1c to your computer and use it in GitHub Desktop.
Save razielgn/03ddb0f2557b77135f1c to your computer and use it in GitHub Desktop.
Key-Value Store for Codebrawl

A restful KV store

It relies on Sinatra to make everything pretty. Persistence is achieved with Marshal.

Methods

GET

curl "http://kvserver.dev/key1"
#=> value1

SET

curl -d "value3" "http://kvserver.dev/key3"
#=> value3

DELETE

curl -X delete "http://kvserver.dev/key3"
#=> value3

KEYS

curl "http://kvserver.dev"
#=> key1
    key2
    ...
require 'sinatra/base'
class KVStore < Sinatra::Base
set :file, "store.msh"
set :logging, true
configure do
Store = Marshal.load(File.read settings.file) rescue {}
end
helpers do
def save_to_disk
open(settings.file, "w") do |f|
f.write Marshal.dump(Store)
end
end
end
before('/*') do
@key = params[:splat].first
end
after '/*' do
# Write to disk only on actual changes
save_to_disk if env["REQUEST_METHOD"] =~ /post|delete/i and not body.empty?
end
get('/') { body Store.keys.join("\n") } # KEYS
get('/*') { body Store[@key] } # GET
post('/*') { body Store[@key] = params.flatten.first } # SET
delete('/*') { body Store.delete(@key) } # DELETE
end
KVStore.run! if __FILE__ == $0
require './store'
require 'rack/test'
describe KVStore do
include Rack::Test::Methods
def app; KVStore; end
let(:pairs){ {"test/key" => "test/value", "test/key2" => "test/value2"} }
before(:each){ KVStore::Store.clear; KVStore::Store.merge! pairs }
it 'should get a value' do
pairs.each_pair do |k, v|
get("/#{k}"){ |res| res.body.should == v }
end
end
it 'should set a value' do
post "/new/test", "5"
last_response.body.should == "5"
end
it 'should remove a key' do
pairs.each_pair do |k, v|
delete("/#{k}"){ |res| res.body.should == v }
end
end
it 'should get all the keys' do
get("/"){ |res| res.body.should == pairs.keys.join("\n") }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment