Skip to content

Instantly share code, notes, and snippets.

@snipsnipsnip
Last active August 24, 2019 15:37
Show Gist options
  • Save snipsnipsnip/162790 to your computer and use it in GitHub Desktop.
Save snipsnipsnip/162790 to your computer and use it in GitHub Desktop.
book.cgi (requires ruby)
#!/usr/local/bin/ruby
require 'webrick/cgi'
BookFile = 'book.txt'
class Book
attr_reader :page
def initialize(io, page)
@io = io
@page = page
end
def html
return left if text.nil?
"#{right} #{page}<hr>#{text}<hr>#{right} #{page} #{left}"
end
private
def paragraph_at(n)
n.times { @io.gets('') }
@io.gets('')
end
def read_text
text = paragraph_at(@page)
text && text.chomp.gsub(%_\n_, ' ')
end
def text
@text ||= read_text
end
def link(text, href)
%_<a href="#{href}">#{text}</a>_
end
def left
if 0 < page
''
else
link('<', "./?#{page - 1}")
end
end
def right
link('>', "./?#{page + 1}")
end
end
class BookCGI < WEBrick::CGI
def do_GET(req, res)
page = req.query_string ? req.query_string.to_i : 1
html = open(BookFile) {|f| Book.new(f, page).html }
res["content-type"] = "text/html"
res.body = html
end
end
BookCGI.new.start if __FILE__ == $0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment