Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active February 28, 2024 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/80ffc1fb525ba89e45b10beff035d96e to your computer and use it in GitHub Desktop.
Save havenwood/80ffc1fb525ba89e45b10beff035d96e to your computer and use it in GitHub Desktop.
An example of streaming a Rack response with Trenni streaming templates https://github.com/ioquatix/trenni#readme
# frozen_string_literal: true
require 'trenni/template'
##
# Streaming template
TEMPLATE = Trenni::Template.load(<<~'HTML')
<!DOCTYPE html>
<html lang="en">
<head>
<title><?r Model::TITLE ?></title>
<style>
table {
border-collapse: collapse;
box-shadow: 0 0 20px Gainsboro;
font-family: system-ui;
}
table tr:nth-of-type(even) {
background-color: AliceBlue;
}
table td {
padding: 1rem;
}
</style>
</head>
<body>
<table>
<?r Model.rows.each do |row| ?>
<tr>
<?r row.each do |column| ?>
<?r sleep 1 ?>
<td>#{column}</td>
<?r end ?>
</tr>
<?r end ?>
</table>
</body>
</html>
HTML
##
# Data for the template
module Model
TITLE = 'Table of Numbers'
def self.rows = Array.new(3) { Array.new(4) { rand 10..99 } }
end
##
# 404 page
NOT_FOUND_HTML = <<~HTML
<!DOCTYPE html>
<html lang="en">
<head><title>Not Found</title></head>
<body><h1>Not Found</h1></body>
</html>
HTML
##
# Rack app
HEADERS = {'content-type' => 'text/html'}.freeze
BODY_NOT_FOUND = [NOT_FOUND_HTML].freeze
BODY = TEMPLATE.to_proc.freeze
run do |env|
case env.transform_keys { _1.to_sym.downcase }
in {path_info: '/', request_method: 'GET' | 'HEAD'}
[200, HEADERS.dup, BODY]
else
[404, HEADERS.dup, BODY_NOT_FOUND]
end
end
# frozen_string_literal: true
source 'https://rubygems.org'
gem 'trenni'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment