#!/usr/bin/env ruby
# WEB_DIR here:
require_relative 'init'
require 'pg'
DB = PG::Connection.new(dbname: 'd50b', user: 'd50b')
###########################################################################
# Turn comments in the database into static HTML on disk, for faster serving
###########################################################################
# format HTML: hyperlink URLs and turn linebreak to <br>
def fmt(html)
html.gsub(%r{(^|\s)(https?://\S+)}, '\1<a href="\2">\2</a>').gsub("\n", '<br>')
end
# a single comment list entry, used in ol map, below
def li(row)
'<li id="comment-%d"><cite>%s (%s) <a href="#comment-%d">#</a></cite><p>%s</p></li>' %
[row['id'], row['name'], row['created_at'], row['id'], fmt(row['html'])]
end
# the top-level map of database rows into HTML list
def ol(rows)
rows.inject('<ol>') {|html, row| html += li(row) ; html} + '</ol>'
end
# given a db connection & uri, return the HTML comments, ready to write
def qry(db, uri)
res = db.exec_params("select id, created_at, name, html
from i.comments
where uri = $1
order by id", [uri])
return '' if res.ntuples == 0
ol(res)
end
# first write them all
puts "writing all"
DB.exec("select distinct(uri) from i.comments").column_values(0).each do |uri|
wput('commentcache/' + uri, qry(DB, uri))
end
# now listen for changes, and re-write when changed
puts "listening"
DB.exec("listen comments_changed")
while true do
DB.wait_for_notify do |event, pid, uri|
print "#{uri}, "
wput('commentcache/' + uri, qry(DB, uri))
end
end