Created
August 2, 2011 17:40
-
-
Save atamis/1120738 to your computer and use it in GitHub Desktop.
A simple URL shortened in Sinatra with Mongoid.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra' | |
require 'mongoid' | |
configure do | |
Mongoid.configure do |config| | |
name = "url_shortener" | |
host = "localhost" | |
config.master = Mongo::Connection.new.db(name) | |
config.persist_in_safe_mode = false | |
end | |
end | |
class Url | |
include Mongoid::Document | |
field :url, :type => String | |
field :ident, :type => String | |
before_create :set_ident | |
validates_presence_of :url | |
validates_format_of :url, :with => URI::regexp(%w(http https)), :message => "not valid URL" | |
validates_uniqueness_of :url, message: "already taken" | |
private | |
# Generate a unique identifier for the URL. | |
def set_ident | |
loop do | |
ident = ActiveSupport::SecureRandom.urlsafe_base64(5) | |
if self.class.where(ident: ident).count == 0 # Loop until it's unique. | |
self.ident = ident | |
break | |
end | |
end | |
end | |
end | |
get '/' do | |
"POST URL to make new, GET an ident to redirect" | |
end | |
post '/' do | |
url = Url.find_or_create_by(url: params["url"]) | |
if url.errors.empty? | |
url.ident | |
else | |
url.errors.to_json | |
end | |
end | |
get '/:ident' do |ident| | |
url = Url.where(ident: ident).last | |
if url | |
redirect url.url, "Go to #{url.url}\n" | |
else | |
404 | |
end | |
end | |
get '/:ident.json' do |ident| | |
url = Url.where(ident: ident).last | |
if url | |
url.to_json | |
else | |
404 | |
end | |
end | |
error 404 do | |
"Not found" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment