Skip to content

Instantly share code, notes, and snippets.

@hauleth
Forked from amscotti/mongo_urlshortener.rb
Last active December 19, 2015 04:09
Show Gist options
  • Save hauleth/5895507 to your computer and use it in GitHub Desktop.
Save hauleth/5895507 to your computer and use it in GitHub Desktop.
Simple Sinatra + Mongoid URL shortener (untested)
source 'https://rubygems.org'
gem 'sinatra'
gem 'slim'
gem 'mongoid'
gem 'bson_ext'
require 'rubygems'
require 'bundler'
Bundler.require
configure do
Mongoid.configure do |config|
config.sessions = {
default: { hosts: %w[localhost:27017], database: 'urlshortner' }
}
config.raise_not_found_error = false
end
end
class Shorten
include Mongoid::Document
include Mongoid::Timestamps::Created
field :url, type: String
field :shorten, type: String
field :count, type: Integer, default: 0
index({shorten: 1}, {unique: true, name: 'shorten_id'})
end
get '/' do
@shortens = Shorten.desc(:created_at).limit(10)
slim :index
end
post '/create' do
@shorten = Shorten.find_or_create_by(url: params[:shorten][:url])
@shorten.shorten ||= Shorten.count.to_s(36)
@shorten.save
redirect "/#{@shorten.shorten}/info"
end
get '/:id' do |id|
@shorten = Shorten.find_by(shorten: id)
redirect '/' unless @shorten
@shorten.inc(:count, 1)
redirect @shorten.url
end
get '/:id/info' do |id|
@shorten = Shorten.find_by(shorten: id)
redirect '/' unless @shorten
slim :info
end
__END__
@@layout
doctype html
html
head
title Sinatra and MongoMapper Url Shortener
body
== yield
@@index
form action="/create" method="post"
div
label for="url"
| URL:
input#url type="url" placeholder="http://" name="shorten[url]"
div
input type="submit" value="Submit"
input type="reset" value="Clear"
#list style="margin-top: 20px;"
- @shortens.each do |shorten|
div
span.url style="margin-right: 50px;"
a href="/#{shorten.shorten}"
= shorten.url
span.count style="margin-right: 50px;"
= shorten.count
span.info style="margin-right: 50px;"
a href="/#{shorten.shorten}/info"
| Info Page
@@info
div
p: URL: #{@shorten.url}
p: Shorten URL: http://#{request.host}/#{@shorten.shorten}
p: Created at: #{@shorten.created_at}
p: Count: #{@shorten.count}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment