~sivers/sive.rs

sive.rs/script/comments.rb -rwxr-xr-x 1.5 KiB
5fcf6634 — Derek Sivers cover and hardcover 19 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/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