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
some_work
end
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 = Regexp.new "(.)*no #{command.to_s} in(.)*"
installed = !expression.match line
end
return (installed ? yield : false)
end
end
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:
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.
Post a Comment