{ |one, step, back| } 1 of 1 article WikiSyndicate: full/short

Using WEBrick   19 Mar 04
[ print link all ]
Several folks (e.g. Kevin Altis, Aaron Brady) have written about a single line web browser in Python. I wondered what it would look like in Ruby. Here’s one answer…
  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?

 

Formatted: 20-Jul-08 20:31
Feedback: jim@weirichhouse.org