Rake tips & tricks

| updated

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.

Sharing the result of a computation among tasks

If you want to run an expensive operation once and use its result in multiple tasks, just define a dependency task that updates a global variable.

result = 0

task :once do
  result += 1
end

task t1: [:once] do |t|
  puts "#{t.name}: #{result}"
end

task t2: [:once] do |t|
  puts "#{t.name}: #{result}"
end

task t3: [:t1, :t2] do |t|
  puts "#{t.name}: #{result}"
end

task :t0 do |t|
  puts "#{t.name}: #{result}"
end

Task 3 will invoke tasks 1 and 2, but the result will only be updated once:

$ rake t3
t1: 1
t2: 1
t3: 1

A task that doesn’t need this variable can still be run without invoking the expensive task.

$ rake t0
t0: 0

A more realistic example: generating a navbar that is injected into different templates when building a website. Running rake clean will skip this step, and running the build tasks will only run it once.