Tryit
Another approach to Rail's Object#try. This is the result of a StackOverflow discussion between Sergey Gopkalo and Michael Kohl.
Instead of
obj.try(:met1).try(:met2).try(:met3).to_syou can do this
obj.tryit { met1.met2.met3.to_s }or this (the preferred form):
tryit { obj.met1.met2.met3.to_s }You can customize which exception to catch:
TryIt.exceptions << ZeroDivisionError
tryit { 1/0 } # will not raise exceptionsThere's also the possibility to define your own exception handlers:
TryIt.handler = lambda { |_| puts "message from tryit" }
tryit { raise NoMethodError } # will print "message from tryit"Installation
Add this line to your application's Gemfile:
gem 'tryit'
And then execute:
$ bundle
Or install it yourself:
$ gem install tryit
Todo
- Find a way to make the exception list not global.
License
Lincesend under the MIT license. See the provided LICENSE file for details.
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Added some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request