Friday, August 8, 2008

Ruby return & ensure gotcha

If you have return and ensure in your method, be very very careful. What happens is when you call return, the method will not return immediately, but it will execute the ensure block.

This can become a problem on Rails and I guess most of other things.


def some_action
return render :action => 'something' if some_condition
# do other things
rescue Exception => ex
# handle exception
ensure
if other_condition
render :action => 'other_thing'
else
render :action => 'default'
end
end


Let's say some_condition is true, you'll end up with the render inside ensure block and things will get double rendering fun.

1 comments:

Wolf said...

Regular expression is really wonderful to parsing HTML or matching pattern. I use this a lot when i code. Actually when I learn any new langauge, first of all I first try whether it supports regex or not. I feel ezee when I found that.

http://icfun.blogspot.com/2008/04/ruby-regular-expression-handling.html

Here is about ruby regex. This was posted by me when I first learn ruby regex. So it will be helpfull for New coders.