leah / tinytinyurl
- Source
- Commits
- Network (3)
- Issues (0)
- Downloads (0)
- Wiki (1)
- Graphs
-
Tree:
61e59ce
tinytinyurl / tinytiny.rb
| 61e59ced » | leah | 2009-04-10 | 1 | #tinytiny.rb | |
| 2 | # My first Ruby/Sinatra app, a URL shortener. | ||||
| 3 | # by Leah Culver (http://github.com/leah) | ||||
| 4 | require 'rubygems' | ||||
| 5 | require 'sinatra' | ||||
| 6 | require 'sequel' | ||||
| 7 | |||||
| 8 | # Base36 encoded | ||||
| 9 | BASE = 36 | ||||
| 10 | |||||
| 11 | configure do | ||||
| 12 | DB = Sequel.sqlite | ||||
| 13 | DB.create_table :tinyurls do | ||||
| 14 | primary_key :id | ||||
| 15 | String :url | ||||
| 16 | end | ||||
| 17 | end | ||||
| 18 | |||||
| 19 | get '/' do | ||||
| 20 | # Form for entering a fatty URL | ||||
| 21 | <<-end_form | ||||
| 22 | <h1>Tiny tiny URLs!</h1> | ||||
| 23 | <form method='post'> | ||||
| 24 | <input type="text" name="url"> | ||||
| 25 | <input type="submit" value="Make it tiny!"> | ||||
| 26 | </form> | ||||
| 27 | end_form | ||||
| 28 | end | ||||
| 29 | |||||
| 30 | post '/' do | ||||
| 31 | # Put the fatty URL in the database and display | ||||
| 32 | items = DB[:tinyurls] | ||||
| 33 | id = items.insert(:url => params[:url]) | ||||
| 34 | url = request.url + id.to_s(BASE) | ||||
| 35 | "Your tiny tiny url is: <a href='#{url}'>#{url}</a>" | ||||
| 36 | end | ||||
| 37 | |||||
| 38 | get '/:tinyid' do | ||||
| 39 | # Resolve the tiny URL | ||||
| 40 | items = DB[:tinyurls] | ||||
| 41 | id = params[:tinyid].to_i(BASE) | ||||
| 42 | url = items.first(:id => id) | ||||
| 43 | redirect url[:url] | ||||
| 44 | end | ||||
