enabled base62 randomizing of URL

This commit is contained in:
Andrew Davidson 2010-09-14 13:00:03 +08:00
parent 894815ec2b
commit 10a90c6863
4 changed files with 42 additions and 14 deletions

View file

@ -3,4 +3,5 @@ source :gemcutter
gem "rack"
gem "sinatra"
gem "sequel"
gem "pg"
gem "pg"
gem "anybase"

View file

@ -27,4 +27,5 @@ require 'sinatra'
#$stderr.reopen(log)
require 'main'
run Sinatra::Application

View file

@ -1,4 +1,7 @@
require 'anybase'
class ShortenUrl < Sequel::Model
plugin :validation_helpers
unless table_exists?
set_schema do
primary_key :id
@ -8,25 +11,47 @@ class ShortenUrl < Sequel::Model
end
create_table
end
def validate
super
validates_presence [:url, :key]
validates_unique :url
validates_unique :key
end
def short_url
"#{Shorten.base_url}#{Shorten.shortener.to_s(id)}"
"#{Shorten.base_url}#{self.key.to_s}"
end
def self.create_url(link)
uri = URI::parse(link)
raise "Invalid URL" unless uri.kind_of? URI::HTTP or uri.kind_of? URI::HTTPS
uri = URI::parse(link)
raise "Invalid URL" unless uri.kind_of? URI::HTTP or uri.kind_of? URI::HTTPS
# url = self.filter(:url => link).first
# if !url
# max_id = self.order(:id.desc).first
# if !max_id
# max_id = 0
# else
# max_id = max_id.id
# end
# url = self.new(:url => link)
# url.save
# end
url = self.filter(:url => link).first
if !url
max_id = self.order(:id.desc).first
if !max_id
max_id = 0
else
max_id = max_id.id
if !url
key = Anybase::Base62.random(Shorten.path_size)
key_check = self.filter(:url => key).first
while key_check
key = Anybase::Base62.random(Shorten.path_size)
key_check = self.filter(:url => key).first
end
url = self.new(:url => link)
url.save
url = self.new(:url => link, :key => key)
url.save
end
url

View file

@ -12,7 +12,8 @@ configure do
Shorten = OpenStruct.new(
:base_url => "http://xn--8gi.ws/",
:service_name => "&#x27bc;.ws",
:button_text => "&#x27bc;"
:button_text => "&#x27bc;",
:path_size => 4
)
$LOAD_PATH.unshift(File.dirname(__FILE__) + '/lib')
@ -97,7 +98,7 @@ get %r(/(api-){0,1}create) do |api|
end
end
post '/new' do
post '/' do
validate_link params[:url]
url = ShortenUrl.create_url(params[:url])