RubyFlow : The Ruby Community Blog

Home   Submit   Sign Up   Log In   leaders   Twitter   RSS Feed  
 

tryit -- An alternative to Object#try

After a discussion on StackOverflow, we whipped up an alternative to Rails Object#try called tryit. This could be useful if you need similar functionality in pure Ruby or if chaining try calls annoys you. [Ed: moved code examples into comment]

Comments


tryit { "foo".revers.capitalize }
#=> nil
tryit { "foo".reverse.captalize }
#=> nil
tryit { "foo".reverse.capitalize }
#=> "Oof"

You can also add exceptions to handled:

tryit { 1/0 }
ZeroDivisionError: divided by 0
TryIt.exceptions #=> [NoMethodError, ZeroDivisionError]
tryit { 1/0 }
#=> nil

Last but not least you can also overwrite the handler:

TryIt.handler = ->(e) { puts "Something went wrong!" }
#=> #<Proc:0x000000011f6070@(irb):16 (lambda)>
tryit { 1/0 }
Something went wrong!
#=> nil

This is just a quick proof of concept, suggestions and improvements welcome!PeterCooper - August 15, 2012 06:54

Post a Comment

Comment abilities for non registered users are currently deactivated, pending time to add a proper CAPTCHA to solve the escalating spam problem. Sorry!