Created
August 8, 2008 01:41
-
-
Save vroy/4531 to your computer and use it in GitHub Desktop.
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 "rubygems" | |
require 'sequel' | |
require "sinatra" | |
DB = Sequel.connect 'sqlite://blog.db' | |
class Post < Sequel::Model(:posts) | |
set_schema do | |
primary_key :id | |
varchar :title | |
timestamp :created_at | |
text :body | |
end | |
create_table unless table_exists? | |
end | |
get '/' do | |
if Post.dataset.count == 0 | |
"There are no posts<br />#{new_post_link}" | |
else | |
"<ul>#{Post.all.collect {|post| "<li>#{edit_post_link(post[:id])} - | |
<a href='#{post[:id]}'>#{post[:title]}</a> - #{post[:body]}</li>"}}</ul><br />#{new_post_link}" | |
end | |
end | |
get '/new' do | |
<<-eos | |
<h3>Add a new post</h3> | |
<form action='/create' method='post'> | |
<label for='title'>Title</label><br /> | |
<input type='text' name='title' /><br /> | |
<label for='body'>Body</label><br /> | |
<textarea name='body'></textarea><br /> | |
<input type='submit' name='submit' value='Add' /> | |
</form> | |
eos | |
end | |
post '/create' do | |
title, text = params[:title], params[:body] | |
Post.create :title => title, :body => text | |
redirect '/' | |
end | |
get '/:id' do | |
post = Post[params[:id].to_i] | |
<<-eos | |
<h3>#{post[:title]}</h3> | |
<p>#{post[:body]}</p> | |
<p><a href="/">home</p></p> | |
eos | |
end | |
get '/edit/:id' do | |
post = Post[params[:id].to_i] | |
id, title, body = post[:id], post[:title], post[:body] | |
<<-eos | |
<h3>Edit post</h3> | |
<form action='/#{id}' method='post'> | |
<label for='title'>Title</label><br /> | |
<input type='text' name='title' value=#{title} /><br /> | |
<label for='body'>Body</label><br /> | |
<textarea name='body'>#{body}</textarea><br /> | |
<input type='hidden' name='_method' value='PUT' /> | |
<input type='submit' name='submit' value='Update' /> | |
</form> | |
eos | |
end | |
put '/:id' do | |
title, text = params[:title], params[:body] | |
if Post.filter(:id => params[:id].to_i).update(:title => title, :body => text) | |
body "Edited successfully: <a href='/'>Home</a>" | |
else | |
body "There was an error" | |
end | |
end | |
### HELPERS ### | |
helpers do | |
def new_post_link | |
"<a href='/new'>Add</a> a new post" | |
end | |
def edit_post_link(id) | |
"<a href='/edit/#{id}'>edit</a>" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment