Skip to content

Instantly share code, notes, and snippets.

@Overbryd
Created June 17, 2011 18:15
Show Gist options
  • Save Overbryd/1031943 to your computer and use it in GitHub Desktop.
Save Overbryd/1031943 to your computer and use it in GitHub Desktop.
Super easy key value store for Code Challenge #2 (https://gist.github.com/1029706)
#!/usr/bin/env ruby
require 'rubygems'
require 'gli'
require 'yajl/json_gem'
require 'uuid'
include GLI
ENDTAG = "\x5f\x5fEND\x5f\x5f"
pre do
$data = JSON::load(DATA.read) rescue {}
$uuid = UUID.new
end
post do
source = File.read(__FILE__).split(ENDTAG).first
File.open(__FILE__, 'w') do |f|
f.write("#{source}\n#{ENDTAG}\n#{$data.to_json}")
end
end
desc "Get a key/value pair by id"
command :get do |c|
c.action do |global_options, options, args|
value = $data[args.first]
puts({ args.first => value }.to_json)
end
end
desc "Create/update a key/value pair"
command :set do |c|
c.arg_name 'unique_key'
c.flag [:k, :key]
c.action do |global_options, options, args|
uuid = options[:k] || $uuid.generate
begin
value = JSON::parse(args.first)
rescue JSON::ParserError
value = args.first
end
$data[uuid] = value
puts({uuid => value}.to_json)
end
end
desc "Delete a key and its value"
command :delete do |c|
c.action do |global_options, options, args|
puts({args.first => $data.delete(args.first)}.to_json)
end
end
desc "List all keys stored in the db"
command :keys do |c|
c.switch [:p, :pretty]
c.action do |global_options, options, args|
puts Yajl::Encoder.encode($data.keys, :pretty => options[:p], :indent => ' ')
end
end
desc "List all entries"
command :list do |c|
c.switch [:p, :pretty]
c.action do |global_options, options, args|
puts Yajl::Encoder.encode($data, :pretty => options[:p], :indent => ' ')
end
end
exit run(ARGV)
__END__
{}
require 'rubygems'
require 'sinatra'
require 'yajl/json_gem'
require 'uuid'
$data = JSON::load(File.read('dump.json')) rescue {}
$uuid = UUID.new
before do
content_type 'application/json', :charset => 'utf-8'
end
get '/_keys' do
$data.keys.to_json
end
post '/_persist' do
JSON.dump($data, File.open('dump.json', 'w'))
{ '_persist' => 'done' }
end
get '/:id' do
value = $data[params[:id]]
status 404 unless value
{ params[:id] => value }.to_json
end
post '/' do
uuid = $uuid.generate
$data[uuid] = params[:data]
{uuid => params[:data]}.to_json
end
put '/:id' do
status 201 unless $data.has_key?(params[:id])
$data[params[:id]] = params[:data]
{params[:id] => params[:data]}.to_json
end
delete '/:id' do
status 204
{params[:id] => $data.delete(params[:id])}.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment