All Articles

40 Lines URL Shortener App

Here is my another 40 lines simple ruby app, URL Shortener App.
I use a Base 62(0-9, A-Z, a-z) numbering system to represent the row id. And Fortunately, Ruby already has a library for it, The alphadecimal gem :)

%w(sinatra dm-core dm-migrations haml alphadecimal uri).each { |lib| require lib}

get '/' do haml :index end	

get '/:url' do redirect Url.first(:id => params['url'].alphadecimal).origin end

post '/' do
  uri = URI::parse(params['origin'])	
  raise "Invalid URL" unless uri.kind_of? URI::HTTP or uri.kind_of? URI::HTTPS
  @url = Url.first_or_create(:origin => uri.to_s)
  haml :index
end

class Url
  include DataMapper::Resource
  property :id, Serial
  property :origin, String
  
  def alias() self.id.alphadecimal end
end

configure do
  DataMapper.setup(:default, "sqlite:///development.sqlite3")
  DataMapper.auto_migrate!
end

__END__

@@ index
%html
	%head
		%title Klik - Url Shortener App
	%body
		%h1 Klik - Url Shortener App
		- unless @url.nil? 
			%code= @url.origin
			%a{:href => env['HTTP_REFERER'] + @url.alias}= env['HTTP_REFERER'] + @url.alias
		%form{:action => '/', :method => 'POST'}
			%input{:type => 'text', :name => 'origin'}
			%input{:type => 'submit', :value => 'Pendekin!'}