Skip to content

Instantly share code, notes, and snippets.

Created Mar 25, 2021
What would you like to do?
How to Build a Web App with and without Rails Libraries
# Persistent storage with SQLite:
# Use SQLite to store data instead
# of YAML
require 'rack'
require 'rack/handler/puma'
# Require the sqlite3 gem
require 'sqlite3'
app = -> environment {
request =
response =
# Create a SQLite3 Database Object
database ="mirth.sqlite3", results_as_hash: true)
if request.get? && request.path == "/show/birthdays"
response.content_type = "text/html; charset=UTF-8"
# Get all birthdays from the database
all_birthdays = database.execute("SELECT * FROM birthdays")
all_birthdays.each do |birthday|
response.write "<li> #{birthday['name']}</b> was born on #{birthday['date']}!</li>\n"
response.write "</ul>\n"
response.write <<~STR
<form action="/add/birthday" method="post" enctype="application/x-www-form-urlencoded">
<p><label>Name <input type="text" name="name"></label></p>
<p><label>Birthday <input type="date" name="date"></label></p>
<p><button>Submit birthday</button></p>
elsif && request.path == "/add/birthday"
new_birthday = request.params
# Create a query to add the new data
query = "INSERT INTO birthdays (name, date) VALUES (?, ?)"
database.execute(query, [new_birthday['name'], new_birthday['date']])
response.redirect('/show/birthdays', 303)
response.content_type = "text/plain; charset=UTF-8"
response.write("✅ Received a #{request.request_method} request to #{request.path}!")
}, :Port => 1337, :Verbose => true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment