On Tue, Feb 1, 2011 at 12:09 AM, I=F1aki Baz Castillo <ibc / aliax.net> wrote=
:
> Hi, my program invokes "exit true" or "exit false" and I want to catch
> such return code into at_exit() block, but I don't know how to do
> that.


> I would like something as:
>
>
> at_exit(exit_status) {
> =A0puts "exiting with status #{status}"
> }
>
> if SOMETHING
> =A0exit true
> else
> =A0exit false
> end

You are aware that you can simplify that to

exit SOMETHING

are you?

> Of course I call "exit" from lof of clases/modules under my project so
> I cannot use a local scope variable "status" (and I wouldn't like to
> use a global variable).

First of all: IMHO that is bad practice because it prevents your code
to be used in different situations (i.e. reduces modularity).  The
proper way would be to raise exceptions and deal with them
appropriately.  You can even omit the handling on top level and get
appropriate exit codes of the process (i.e. 0 for the regular case, 1
for error):

$ ruby19 -e 'raise "f"'; echo $?
-e:1:in `<main>': f (RuntimeError)
1
$ ruby19 -e 'nil'; echo $?
0
$

However, you can do what you want with a rescue clause:

begin
  # main code
rescue SystemExit =3D> e
  puts "exiting with status #{e.status}"
  raise
rescue Exception =3D> e
  puts "exiting with status 1"
  raise
else
  puts "exiting with status 0"
end

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/