The blog of Rahoul Baruah from 3hv Ltd

What's going on?

My name is Rahoul Baruah (aka Baz) and I'm a software developer in Leeds (England).

This is a log of things I've discovered while writing software in Ruby on Rails. In other words, geek stuff.

However, I've decided to put this blog on ice - I would ask you to check out my business blog here (or subscribe here).

16 September, 2007

Testing for Unix commands on the path in Ruby

Recently we needed to run some tests against our application. However, the application shells out and uses a couple of Unix commands to do some of its work - commands that were not installed on my dev box at the time. Rather than ignoring failing tests (something, like ignoring warnings, I find really hard to do) I thought I should alter the tests to only run if the Unix command was present. After some discussion with Peter he came up with the following syntax:

using :some_command do

Pretty nice - if some_command is available then the block is executed, otherwise nothing happens.

(By the way, the code below is (c) 2007 Rahoul Baruah and is available under the LGPL and is not the same as the code that actually made it into our application. [Legal stuff over])

require 'open3'

module UnixTools

def using command
raise "USING: you must supply a block when calling using" unless block_given?

installed = false
Open.popen3("which #{command.to_s}") do | stdin, stdout, stderr |
line = stdout.readline.chomp
expression = "(.)*no #{command.to_s} in(.)*"
installed = !expression.match line

return (installed ? yield : false)


Stick this in a file called "unix_tools.rb" in your lib folder, make sure which is on your path and use!

One caveat - Peter started getting EOFs - because he was using the version of which that came with Fink. which on OSX returns "no COMMAND in $PATH", which on CentOS returns "/usr/bin/which: no COMMAND in $PATH" but which in Fink returns EOF. As soon as he switched to /usr/bin/which it worked fine. YMMV, as ever.

1 comment:

Peter said...

Well, you say I came up with the syntax, as I remember it, it came out of a group discussion. Still, thanks for the quote.

eXTReMe Tracker