ruby -rwebrick -e 'WEBrick::HTTPServer.new(:Port=>8000,:DocumentRoot=>".").start'
Since WEBrick defaults to port 80 and doesn’t use the current directory as the document root by default, we have to add that information to the command line.
Although interesting, I find the following script more useful than a single line command. I often generate HTML docs on a machine at work that doesn’t have a web server, nor file system that is available to my browser’s "file:" protocol. So I fire up the "servefiles.rb" script below.
#!/usr/local/bin/ruby
require 'webrick'
include WEBrick
dir = Dir::pwd
port = 12000 + (dir.hash % 1000)
puts "URL: http://#{Socket.gethostname}:#{port}"
s = HTTPServer.new(
:Port => port,
:DocumentRoot => dir
)
trap("INT"){ s.shutdown }
s.start
Notice that the port is calculated from a hash function on the directory name. This allows me to run multiple mini-webservers in different directories. The script prints out the URL (with port number) when it starts, so I just cut and paste the URL into the browser to see the served files.
How do you use WEBrick?