Skip to content

Instantly share code, notes, and snippets.

@runemadsen
Created September 28, 2012 01:09
Show Gist options
  • Save runemadsen/3797418 to your computer and use it in GitHub Desktop.
Save runemadsen/3797418 to your computer and use it in GitHub Desktop.
Creating a blog in Sinatra and Datamapper
require 'sinatra'
require 'dm-core'
DataMapper::setup(:default, {:adapter => 'yaml', :path => 'db'})
class BlogPost
include DataMapper::Resource
property :id, Serial
property :title, String
property :body, Text
end
DataMapper.finalize
get "/" do
erb :front
end
get "/blog" do
@posts = BlogPost.all
erb :blog
end
get "/blog/new" do
erb :blog_new
end
post "/blog/save" do
myPost = BlogPost.new
myPost.title = params[:title]
myPost.body = params[:body]
if(myPost.save)
@message = "Your post was saved!"
else
@message = "Your post was NOT SAVED!!!!!!!"
end
erb :blog_save
end
get "/blog/:id" do
@post = BlogPost.get(params[:id])
erb :post
end
<% for thisPost in @posts %>
<h1><%= thisPost.title %></h1>
<p><%= thisPost.body %></p>
<a href="http://itp.nyu.edu/~rsm347/sinatra/myblog/blog/<%= thisPost.id %>">Permalink</a>
<% end %>
<form action="http://itp.nyu.edu/~rsm347/sinatra/myblog/blog/save" method="POST">
<p><input type="text" name="title" value="Write your title here" /></p>
<p><textarea name="body">Write your blog post here</textarea></p>
<p><input type="submit" value="Save your post" /></p>
</form>
<h1><%= @message %></h1>
<a href="http://itp.nyu.edu/~rsm347/sinatra/myblog/blog">Go to the blog</a>
<html>
<head>
<title>Runes Blog</title>
</head>
<body>
<h1>Hello</h1>
<a href="http://itp.nyu.edu/~rsm347/sinatra/myblog/blog">Go to the blog</a>
</body>
<html>
<html>
<head>
<title>Runes Blog</title>
</head>
<body>
<%= yield %>
</body>
<html>
<h1><%= @post.title %></h1>
<p><%= @post.body %></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment