Skip to content

@daz4126 /main.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Short, Long and Pretty Urls - Using Sinatra & DataMapper to demonstrate different types of urls
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.