Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails rescuing from 'Errno::ENOENT'

I need to rescue from 'Errno::ENOENT' in a Ruby on Rails 3.0.4 application. I currently have controller with the following code:

begin
  `lame #{parameters}`
rescue Errno::ENOENT
  logger.info "command 'lame' not found: ensure LAME is installed"
end

However, the log code is never called, but the logs show:

script/rails: No such file or directory - lame ...

If I create a ruby script with same snippet, the exception is rescued.

like image 931
Kevin Sylvestre Avatar asked Feb 20 '11 07:02

Kevin Sylvestre


Video Answer


1 Answers

In Ruby 1.8, Errno::ENOENT is not raised by shell execution / back-ticks - the error you're seeing is standard error, printed by the shell. If you want to detect this, I'd recommend looking for an exit code of 127:

`lame #{parameters} 2>&1`
if $?.exitstatus == 127
  logger.info "command 'lame' not found: ensure LAME is installed"
end

However, this will raise Errno::ENOENT in Ruby 1.9.

You might consider checking the output from which lame instead:

lame_installed = system("which lame >/dev/null")
# or even better
lame_available = !(lame_path = `which lame`.strip).empty? && File.executable?(lame_path)

Further reading:

  • http://www.faqs.org/docs/abs/HTML/exitcodes.html
like image 93
wuputah Avatar answered Sep 17 '22 15:09

wuputah