Ruby tips & tricks

Running a web server

For a development web server, similar to the http.server module in Python, install the WEBrick gem. On Debian etc., it is in the ruby-webrick package:

sudo apt install ruby-webrick

It doesn’t come with a CLI like python -m http.server, so it needs to be set up in a Ruby script, as described in the README (/usr/share/doc/ruby-webrick/README.md). For example, as a task in a Rakefile (that also launches the browser):

OUT_DIR = 'www'

desc 'Build site'
task build: do
  sh 'build-site', OUT_DIR
end

desc 'Open site in browser'
task serve: [:build] do
  require 'webrick'
  server = WEBrick::HTTPServer.new Port: 8000, DocumentRoot: OUT_DIR
  sh 'open', 'http://localhost:8000/'
  trap('INT') { server.shutdown }
  server.start
end

The site can then be built and served by running rake serve.

Stop the server by pressing Ctrl-C to send the SIGINT (keyboard interrupt) signal.