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 << ZeroDivisionError #=> [NoMethodError, ZeroDivisionError] tryit { 1/0 } #=> nilLast 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! #=> nilThis is just a quick proof of concept, suggestions and improvements welcome!Post a comment