The Myth of Sysifus (sic)
Here's a cute little snippet that makes my life a lot easier when interacting with the outside world in Ruby.
def sysify script
script.each_line do |l|
system l.strip
end
end
This simple little function allows me to do things like this:
def do_shell_stuff
begin
sysify <<-SETUP
# THIS IS A SHELL SCRIPT
cat /tmp/some.junk | some | util | chain > /tmp/desired.file
run_other_util /tmp/desired.file
do_lots_of_other_shell_stuff
SETUP
# THIS IS NORMAL RUBY CODE
lines = []
open("/tmp/desired.file", "r") do |f|
f.readlines.each { |l| lines << l.strip }
end
ensure
sysify <<-CLEANUP
# THIS IS A SHELL SCRIPT AGAIN
rm /tmp/desired.file
CLEANUP
end
end
I can see this being particularly useful for use in Rake actions involving software builds where you may have to in one action
untar a file, run ./configure, execute a make and then a make install. Doing it with repeated system calls breaks DRY seriously where using sysify puts the calls to system in one place. The only downside I can see is that error handling could start to get hairy: specifically what happens if you expect an error return that's actually a warning from an embedded command?I'll be thinking on that last one next.

0 comments:
Post a Comment