Created
October 26, 2015 08:14
-
-
Save franckverrot/b2d1ec86c1f12ccf63a8 to your computer and use it in GitHub Desktop.
`try` vs `try!` vs `.?` vs `method_missing as a blackhole`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_support' | |
TryIsNotSafe = Class.new(RuntimeError) | |
SafeOperatorIsNotSafe = Class.new(RuntimeError) | |
MethodMissingIsNotSafe = Class.new(RuntimeError) | |
def does_it_raise(&block) | |
begin | |
result = block.call | |
puts "SUCCESS, result: #{result.inspect}" | |
rescue TryIsNotSafe, SafeOperatorIsNotSafe, MethodMissingIsNotSafe => e | |
puts "FAILURE, message: #{e}" | |
end | |
end | |
does_it_raise { nil.try(:foo, (raise TryIsNotSafe)) } # => FAILURE, message: TryIsNotSafe | |
does_it_raise { nil.try!(:foo, (raise TryIsNotSafe)) } # => FAILURE, message: TryIsNotSafe | |
does_it_raise { nil.?foo(raise SafeOperatorIsNotSafe) } # => SUCCESS, result: nil | |
class Object | |
def method_missing(*) | |
end | |
end | |
does_it_raise { nil.foo(raise MethodMissingIsNotSafe) } # => FAILURE, message: MethodMissingIsNotSafe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment