Skip to content

Instantly share code, notes, and snippets.

@jamierumbelow
Created May 4, 2009 20:24
Show Gist options
  • Save jamierumbelow/106645 to your computer and use it in GitHub Desktop.
Save jamierumbelow/106645 to your computer and use it in GitHub Desktop.
############################
# blogging app #
# by Jamie Rumbelow #
# #
# to run: #
# gem install sinatra #
# ruby blog.rb #
############################
# blog.rb
require 'rubygems'
require 'sinatra'
require 'database'
require 'templates'
get '/' do
erb :list
end
get '/new' do
erb :new
end
post '/new' do
db = Database.new
db.save(params)
end
# database.rb
require 'yaml'
class Database
def initialize
@dbcontents = YAML::load_file('database.db')
end
def get(id)
@dbcontents[id]
end
def get_all()
@dbcontents
end
def insert(data)
data['id'] = @dbcontents.length+1
@dbcontents[data['id']] = data
end
def exists?(id)
!@dbcontents[id].nil?
end
def update!(id, data)
@dbcontents[id] = data
end
def close
File.open('database.db', "w") { |file| YAML.dump(@dbcontents, file) }
end
end
# templates.rb
template :layout do
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\">
<meta name=\"author\" content=\"Jamie Rumbelow\">
<meta name=\"description\" content=\"A cool new blogging app, written in an hour to demonstrate Sinatra\">
<title>Rumbelblog</title>
</head>
<body>
<div id=\"header\">
<h1>Rumbelblog</h1>
<h3>An Awesome Little Blogging Engine</h3>
</div>
<div id=\"content\">
<%= yield %>
</div>
<div id=\"footer\">
<p>Rumbelblog is an awesome little blogging engine, written in Sinatra, by <a href=\"http://www.jamierumbelow.net\">Jamie Rumbelow</a>. Standards Valid XHTML1.1 and CSS2.1!</p>
</div>
</body>
</html>"
end
template :list do
"<% for post in @posts %>
<div class=\"post\">
<h2><%= post.title %></h2>
<p><%= post.content %></p>
</div>
<% end %>
<p><a href=\"/new\">New Post</a></p>"
end
template :new do
"<form action=\"/new\" method=\"post\">
Title: <input type=\"text\" name=\"title\" /><br />
Content: <textarea name=\"content\"></textarea><br />
<input type=\"submit\" value=\"Post!\" />
</form>"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment