skip to main |
skip to sidebar
TinyUrl - URL shotener
#tinytiny.rb
# My first Ruby/Sinatra app, a URL shortener.
# by Leah Culver (http://github.com/leah)
require 'rubygems'
require 'sinatra'
require 'dm-core'
# Base36 encoded
BASE = 36
class Tinytiny
include DataMapper::Resource
property :id, Serial
property :url, String
end
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/tiny.sqlite3")
configure do
DataMapper.auto_upgrade!
end
get '/' do
# Form for entering a fatty URL
<<-end_form
<h1>Tiny tiny URLs!</h1>
<form method='post'>
<input type="text" name="url">
<input type="submit" value="Make it tiny!">
</form>
end_form
end
post '/' do
# Put the fatty URL in the database and display
tiny = Tinytiny.new(:url => params[:url])
if tiny.save
url = request.url + tiny.id.to_s(BASE)
"Your tiny tiny url is: <a href='#{url}'>#{url}</a>"
end
end
get '/:tinyid' do
# Resolve the tiny URL
tiny = Tinytiny.first(:id => params[:tinyid].to_i(BASE))
redirect tiny.url
end
No comments:
Post a Comment