A Simple Ruby Runner Script

Will Goring, 12 Oct 2011

Recently I’ve been spending a bit of time getting properly acquainted with Ruby, to which end I’ve picked up a copy of the famous ‘Pickaxe book’, and have been working through the early chapters to give myself a good grounding the language and its core concepts.

So far it’s all going well; the book is excellent and, while it’ll be a while before I’m applying for Ruby programming jobs, I think I’ve got to the point where I can start putting together trivial programmes for my own use. Which is where the book seems to have left me a little high-and-dry. There’s a chapter on how to structure your source directory, which all seems sensible, but when it comes to running your code it leaves you with cding into the source directory and running something like:

bash % ruby -I lib bin/some_ruby_script

That’s fine as far as it goes, but it’s a lot to type every time I want to run something, and it’s sensitive to the CWD, so symlinking it into $PATH or something isn’t an option.

The book then goes into detail about how to package your code up as a Gem and install it on any machine, but that’s more effort than I want to go to for system maintenance scripts and the like, which are only ever going to be run on the machine they’re developed on.

All of which is a long winded explanation of why I wrote this:

It’s a simple shell script designed to be put in the base directory of a ‘standard’ layout Ruby project (where I use ‘standard’ to mean ‘as defined in chapter 16.2 of Programming Ruby 1.91 with the same filename as something in the bin directory. You can then run the script from anywhere, even by symlinking it into a directory in your $PATH, it doesn’t need arguments, but it will pass any you give it through to the ruby application you’re executing.

The way I use it is to have one master copy (actually, one master copy per RVM environment,) stored away somewhere safe, and then put hardlinks to it wherever I have a Ruby command I want to be able to run conveniently from the command line.

The obvious downside to this is that your development copy of your Ruby code is also the copy you run; if that sounds horrible to you (and it probably should,) then you should look into packaging your code as a Gem and installing it properly.

  1. Handily, even if you don’t have the book, that chapter is available as a free excerpt from its Pragmatic Bookshelf page

Filed under:

coding ruby shell