Skip to content

Instantly share code, notes, and snippets.

@franckverrot
Created October 26, 2015 08:14
Show Gist options
  • Save franckverrot/b2d1ec86c1f12ccf63a8 to your computer and use it in GitHub Desktop.
Save franckverrot/b2d1ec86c1f12ccf63a8 to your computer and use it in GitHub Desktop.
`try` vs `try!` vs `.?` vs `method_missing as a blackhole`
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