:wq - blog » monkeypatch http://writequit.org/blog Tu fui, ego eris Mon, 22 Dec 2014 14:54:59 +0000 en-US hourly 1 http://wordpress.org/?v=4.1.5 Nesting traps in Ruby with a quick monkeypatch http://writequit.org/blog/2009/06/09/nesting-traps-in-ruby-with-a-quick-monkeypatch/ http://writequit.org/blog/2009/06/09/nesting-traps-in-ruby-with-a-quick-monkeypatch/#comments Tue, 09 Jun 2009 16:42:55 +0000 http://writequit.org/blog/?p=292 If you end up messing with traps a lot in Ruby, you’ll find that they don’t unbind when leaving function context, so you’re either stuck ‘ensuring’ that the trap is replaced by the old trap, or just dealing with it.

Well, here’s a quick monkeypatch for adding a method that will do all the ensuring/retrapping for you when you leave a function.

Here’s the code (click for github’s colorized version):

While the syntax for calling it (t.trapr_wrap "SIGINT", Proc.new { ... }, :foo) isn’t exactly clean, if you’re calling a lot of functions and only want a trap to be active inside, it beats having to repeat undoing your trap every time.

Update: I changed the code for better readability and because I was doing it a silly way. Now it takes actual arguments instead of just ‘*args’.

]]>
http://writequit.org/blog/2009/06/09/nesting-traps-in-ruby-with-a-quick-monkeypatch/feed/ 0