On Fri, 23 Jun 2006, James Edward Gray II wrote:

> I need to run a script in a special environment.  I need to change how STDIN
> works, for example, to fetch responses from GUI.  That's easily done and can
> be made to work via a simple:
>
>  ruby -r my_special_env script_to_run.rb
>
> However, one element keeps tripping me up.  My special environment must also
> catch exceptions not handled by the script, for error reporting purposes.
> Is there any way to do the via a require?
>
> The best idea I have so far is to add a begin .. rescue .. end around the
> code in the script and then execute it, but this seems mighty clumsy when
> you take into account things like the working directory, the script name,
> and line number offsets.  It's doable, but I would love to find a more
> elegant solution.
>
> Any ideas you can provide are appreciated.
>
> James Edward Gray II
>
>

     harp:~ > cat env.rb
     STDIN.reopen(open(__FILE__))
     at_exit do
       e = $!
       if e
         require 'logger'
         Logger.new(STDERR).fatal{ e }
       end
     end


     harp:~ > cat a.rb
     puts gets
     raise 'foobar'


     harp:~ > ruby -r env.rb a.rb
     STDIN.reopen(open(__FILE__))
     F, [2006-06-23T10:04:35.279359 #15389] FATAL -- : foobar (RuntimeError)
     a.rb:2
     a.rb:2: foobar (RuntimeError)


note that the original behaviour (dumping to STDERR) is also done.  if you
don't want this add in

   at_exit do
     ...
     exit!
   end

regards.

-a
-- 
suffering increases your inner strength.  also, the wishing for suffering
makes the suffering disappear.
- h.h. the 14th dali lama