RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

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 } #=> 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!

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in