Skip to content

Instantly share code, notes, and snippets.

Last active Dec 30, 2021
What would you like to do?
How to Build a Web App with and without Rails Libraries
# mirth-4.rb
# Data persistence with YAML store:
# Use YAML to save the birthdays that
# can be reused when the server restarts
require 'socket'
# Require the library to use YAML::Store
require 'yaml/store'
server =
# Attain file store from a YAML file
store ="mirth.yml")
loop do
client = server.accept
request_line = client.readline
method_token, target, version_number = request_line.split
case [method_token, target]
when ["GET", "/show/birthdays"]
response_status_code = "200 OK"
content_type = "text/html"
response_message = "<ul>\n"
# Get all the birthdays data in a hash object
all_birthdays = {}
store.transaction do
all_birthdays = store[:birthdays]
all_birthdays.each do |birthday|
response_message << "<li> #{birthday[:name]}</b> was born on #{birthday[:date]}!</li>\n"
response_message << "</ul>\n"
response_message << <<~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>
when ["POST", "/add/birthday"]
response_status_code = "303 See Other"
content_type = "text/html"
response_message = ""
all_headers = {}
while true
line = client.readline
break if line == "\r\n"
header_name, value = line.split(": ")
all_headers[header_name] = value
body =['Content-Length'].to_i)
require 'uri'
new_birthday = URI.decode_www_form(body).to_h
# Store the user-input birthday data
# back into the YAML store
store.transaction do
store[:birthdays] << new_birthday.transform_keys(&:to_sym)
response_status_code = "200 OK"
response_message = "✅ Received a #{method_token} request to #{target} with #{version_number}"
content_type = "text/plain"
http_response = <<~MSG
#{version_number} #{response_status_code}
Content-Type: #{content_type}; charset=#{}
Location: /show/birthdays
client.puts http_response
- :name: Gma
:date: 01/01/2021
- :name: Tom
:date: 02/01/2021
- :name: Sesame
:date: 03/01/2021
Copy link

s4na commented Dec 30, 2021

Thank you for the great blog!

I found the typo.
In order for the program to work correctly, there needs to be a line break on the next line after Location: /show/birthdays which is on line 77.

Best regards,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment