public
Created

Short, Long and Pretty Urls - Using Sinatra & DataMapper to demonstrate different types of urls

  • Download Gist
main.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
require 'sinatra'
require 'data_mapper'
require 'slim'
require 'digest/sha1'
 
DataMapper.setup(:default, ENV['DATABASE_URL'] || File.join("sqlite3://",settings.root, "development.db"))
 
class Note
include DataMapper::Resource
property :id, Serial
property :title, String, :required => true
property :content, Text
property :pretty, String, default: -> r,p { r.make_pretty }
property :salt, String, default: -> r,p { (1+rand(8)).to_s }
property :long, String, default: -> r,p { r.make_long }
def make_pretty
title.downcase.gsub(/\W/,'-').squeeze('-').chomp('-')
end
def make_long
Digest::SHA1.hexdigest(Time.now.to_s + title + id.to_s)
end
def short
(id.to_s + salt).reverse.to_i.to_s(36)
end
end
 
get '/' do
@notes = Note.all
slim :index
end
 
post '/' do
note = Note.create params[:note]
redirect '/'
end
 
get '/pretty/:url' do
@note = Note.first(:pretty => params[:url])
slim :show
end
 
get '/short/:url' do
@note = Note.get params[:url].to_i(36).to_s.reverse.chop
slim :show
end
 
get '/long/:url' do
@note = Note.first(:long => params[:url])
slim :show
end
 
__END__
@@layout
doctype html
html
head
meta charset="utf-8"
title Short, Long & Pretty Urls
body
== yield
 
@@index
h1 Notes
form action="/" method="POST"
input type="text" name='note[title]'
br
textarea name='note[content]' rows=12 cols=40
input type="submit" value="Create"
-if @notes.any?
ul#notes
- @notes.each do |note|
li #{note.title} <a href="/pretty/#{note.pretty}">Pretty</a> | <a href="/short/#{note.short}">Short</a> | <a href="/long/#{note.long}">Long</a>
- else
h2 No Notes!
@@show
h1= @note.title
= @note.content

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.