Skip to content

Instantly share code, notes, and snippets.

@latompa
Created September 27, 2011 02:02
Show Gist options
  • Save latompa/1244130 to your computer and use it in GitHub Desktop.
Save latompa/1244130 to your computer and use it in GitHub Desktop.
rlshrtnr.rb
# shorten a URL
# curl -X POST --data "url=http://livingsocial.com" localhost:9292
#
# --> returns the shortened url in the body
#
# to retrieve a shortened URL
# open http://localhost:9292/a723bae
#
require 'rubygems'
require 'rack'
require 'zlib'
HTTP_HOST = "http://localhost:9292"
class Shortener
def initialize
@url_store = {}
end
def store_url(url)
key = Zlib.adler32(url).to_s(26)
@url_store[key] = url
"#{HTTP_HOST}/#{key}"
end
def get_url(key)
@url_store[key.gsub(/^\//,"")]
end
def call(env)
case env['REQUEST_METHOD']
when "GET"
url = get_url env['REQUEST_URI']
if url
[302, {"Location" => url}, ""]
else
[404, {}, "Hello Rack!"]
end
when "POST"
post_data = env["rack.input"].readline
_, url = post_data.split(/=/)
shortened = store_url(url)
[201, {}, shortened]
else
[500, {}, "Not implemented !"]
end
end
end
Rack::Handler::Mongrel.run Shortener.new, :Port => 9292
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment