Skip to content

Instantly share code, notes, and snippets.

@ShopifyEng

ShopifyEng/mirth-7.rb Secret

Created Mar 25, 2021
Embed
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 = Rack::Request.new(environment)
response = Rack::Response.new
# Create a SQLite3 Database Object
database = SQLite3::Database.new("mirth.sqlite3", results_as_hash: true)
if request.get? && request.path == "/show/birthdays"
response.write("<ul>\n")
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"
end
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>
</form>
STR
elsif request.post? && 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)
else
response.content_type = "text/plain; charset=UTF-8"
response.write("✅ Received a #{request.request_method} request to #{request.path}!")
end
response.finish
}
Rack::Handler::Puma.run(app, :Port => 1337, :Verbose => true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment