Video transcript & code
I want to share with you one of my favorite Ruby parlor tricks.
The other day I was updating an old website, and I needed to make sure the changes I had made looked right. It was a purely static site, so I just needed something that would serve the files in the current directory to a browser.
In order to do this, I used the following command line:
ruby -run -e httpd . --port=8080
This booted up a Webrick instance, and I was able to test the site.
Let's talk about what's going on here. We'll start by breaking down the command I used.
ruby part is hopefully self-explanatory. Then comes a dash and an 'r'. This is where things get a little sneaky. '-r' is mnemonic for
require. This flag causes Ruby to treat the next argument as the name of a feature and attempt to load it.
Next we supply the library to be required, which is called simply
un. Ruby does not require us to put a space between short-form flags and their arguments, so we can squash them together. The result is that it looks like the word
run… which is exactly what the authors playfully intended when they named the library.
The next flag is
-e, which tells Ruby to execute the following argument as Ruby code. The code we execute is simply a one-word method invocation:
Next we supply the current directory as the directory to serve, and specify a port number.
ruby -r un -e httpd . --port=8080
So what is this mysterious
un library, and this
Let's ask Ruby. As we learned in episode #237, Ruby keeps a list of the library files it has already loaded. We can tell Ruby to load the
un library, and then grep through the
$LOADED_FEATURES list until we find one that ends with
$ ruby -run -e 'puts $LOADED_FEATURES.grep(/un.rb$/)' /home/avdi/.rubies/ruby-2.1.2/lib/ruby/2.1.0/un.rb
Now that we know where to find this library, lets open it up and take a peek inside.
What we find is a is one-file library that offers a number of handy command-line utilities written in pure Ruby. A lot of them we will probably never need, like clones of the UNIX copy and move commands. Although, these might just be useful if we ever wanted to write a simple script that worked the same on Windows as on Linux or Mac OS.
If we scroll down, we can find the
httpd method. It's pretty short and simple. There's come boilerplate for handling command-line flags, and then just enough code to start up a Webrick server, serving the given directory.
And that's really Ruby in a nutshell: it has fun magic tricks, but it's easy to look behind the curtain and learn how to the trick was accomplished. Happy hacking!