Created
June 25, 2013 04:00
-
-
Save jcamenisch/5855837 to your computer and use it in GitHub Desktop.
Return blackhole object with maybe(something), but convert blackhole back to nil with a chain-closing method. Because sometimes we need to send values to outside code that understands the nil idiom, but not our "exotic" blackhole object.
This file contains hidden or 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
class BlackHole | |
def method_missing(*args, &block) | |
self | |
end | |
def unmaybe | |
nil | |
end | |
# ... | |
end | |
def maybe(thing) | |
thing.nil? ? BlackHole.new : thing | |
end | |
class Object | |
def unmaybe | |
self | |
end | |
end | |
a_thing = "A string of sorts." | |
maybe(a_thing)[0..5].downcase.unmaybe #=> "a stri" | |
a_thing = nil | |
maybe(a_thing)[0..5].downcase.unmaybe #=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment