Last active
August 29, 2015 14:05
-
-
Save seejohnrun/4858e232465ab09ae895 to your computer and use it in GitHub Desktop.
tap_try should exist
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
# Mark NoMethodError(s) coming from a call on `nil` | |
class NilClass | |
def method_missing(*) | |
super | |
rescue NoMethodError => e | |
e.instance_variable_set :@real_nil, true | |
raise e | |
end | |
end | |
class Object | |
# Implement a tap_try method to avoid "try-chaining" | |
def tap_try(&block) | |
yield self | |
rescue NoMethodError => e | |
return nil if e.instance_variable_get :@real_nil | |
raise e | |
end | |
end | |
# Usage | |
puts 'hello'.tap_try { |s| s.reverse.length }.inspect # 5 | |
puts nil.tap_try { |s| s.reverse.length }.inspect # nil | |
puts 1.tap_try { |s| s.reverse.length }.inspect # NoMethodError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment