Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby at_exit exit status

Can i determine selves process exit status in at_exit block?

at_exit do
  if this_process_status.success?
    print 'Success'
  else
    print 'Failure'
  end
end
like image 211
tig Avatar asked Jul 17 '09 15:07

tig


People also ask

How to exit a script in Ruby?

Just pass an argument into the exit function. The argument can be a boolean or an integer. If it's boolean, then true means success. If it's an integer than 0 means success.

How do I exit Ruby in terminal?

To exit IRB, type exit at the prompt, or press CTRL+D . You'll return to your shell prompt.

How to stop execution Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop.


2 Answers

using idea from tadman

at_exit do
  if $!.nil? || ($!.is_a?(SystemExit) && $!.success?)
    print 'success'
  else
    code = $!.is_a?(SystemExit) ? $!.status : 1
    print "failure with code #{code}"
  end
end
like image 127
tig Avatar answered Sep 16 '22 15:09

tig


Although the documentation on this is really thin, $! is set to be the last exception that occurs, and after an exit() call this is a SystemExit exception. Putting those two together you get this:

at_exit do
  if ($!.success?)
    print 'Success'
  else
    print 'Failure'
  end
end
like image 28
tadman Avatar answered Sep 17 '22 15:09

tadman