Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Created September 3, 2011 14:25
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 rstacruz/0eccf7a619c14e815a8b to your computer and use it in GitHub Desktop.
Save rstacruz/0eccf7a619c14e815a8b to your computer and use it in GitHub Desktop.
The simplest RESTy database ever

The simplest RESTy database ever

Oh yeah. It totally is.

  • Running it

  • Basic CRUD

    • Adding keys: POST to /your/key/name/here
    • Getting keys: GET /your/key/name/here
    • Deleting keys: DELETE /your/key/name/here
  • Group operations

    • Listing keys: GET /your/key/namespace/ (trailing slash)
    • Deleting groups of keys: DELETE /your/key/namespace/ (trailing slash)

Try it out yourself!

require 'rest_client'
R = RestClient

puts "Adding /people/1          => " + R.post('http://localhost:4567/people/1', name: "Jason", age: "26")
puts "The contents of /people/1 => " + R.get('http://localhost:4567/people/1')
puts "Available keys:           => " + R.get('http://localhost:4567/people/')
puts "Deleting /people/1:       => " + R.delete('http://localhost:4567/people/1')
puts "Available keys:           => " + R.get('http://localhost:4567/people/')

#### Adding /people/1          => OK
#### The contents of /people/1 => {"name":"Jason","age":"26"}
#### Available keys:           => ["/people/1"]
#### Deleting /people/1:       => OK
#### Available keys:           => []
require 'sinatra'
require 'json'
require 'fileutils'
before('*') { |path| @path = File.join(settings.public, path) }
post '*' do # Create/update data
params.delete "splat"
FileUtils.mkdir_p File.dirname(@path)
File.open(@path, 'w') { |f| f.write params.to_json } && "OK"
end
get '*/' do # List keys
Dir["#{@path}*"].select { |f| File.file? f }.map { |f| f.gsub settings.public, '' }.to_json
end
delete '*' do # Delete key(s)
FileUtils.rm_rf(@path) && "OK"
end

Answers to questions you probably have:

  • The getting of keys are handled automatically because they're in /public.
  • Errors will automatically get a non-200 response.
  • Also, crap like http://localhost:4567/foo/../../ will already be trapped by Rack.
  • Running slow? Run it on a ramdisk (and make a cronjob for rsync for persistence) or buy an SSD.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment