Skip to content

Instantly share code, notes, and snippets.

@flippingbits
Created September 1, 2011 15:16
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 flippingbits/98855a25ffdc2257c56a to your computer and use it in GitHub Desktop.
Save flippingbits/98855a25ffdc2257c56a to your computer and use it in GitHub Desktop.

README

This is a key-value store that uses Sinatra. It provides the basic operations GET, SET, DELETE and KEYS.

You can start the application by executing the file app.rb:

ruby app.rb

Make sure that you have installed the gems sinatra and json.

Usage

Now, let's get our hands dirty. By using PUT and the URI http://localhost:4567/key -d "value" we can set a key-value pair. E.g. we can set the key ruby and the value Is awesome:

curl -X PUT http://localhost:4567/ruby -d "Is awesome"

In order to get a key's value, we can use GET and the URI http://localhost:4567/key. E.g. we can get the value of ruby:

curl http://localhost:4567/ruby

If we want to list all keys currently set we can use GET and the URI http://localhost:4567/\_/keys:

curl http://localhost:4567/_/keys

Last but not least: you can delete a key by using DELETE and the URI http://localhost:4567/key. E.g. we can delete the key ruby:

curl -X DELETE http://localhost:4567/ruby

Future Plans

  • Namespaced key-value pairs
require "sinatra"
require "json"
Dir.mkdir("data") unless File.directory?("data")
get "/:key" do |key|
if File.exists?("data/#{key}")
send_file("data/#{key}")
else
[404, "Key #{key} does not exist."]
end
end
get "/_/keys" do
keys = Dir.entries("data") - [".", ".."]
keys.to_json
end
put "/:key" do |key|
data = request.body.read
File.open("data/#{key}", "w") do |f|
f.write(data)
end
"OK."
end
delete "/:key" do |key|
if File.exists?("data/#{key}")
File.delete("data/#{key}")
"OK."
else
[404, "Key #{key} does not exist."]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment