Created
January 4, 2010 23:42
-
-
Save rubiety/268995 to your computer and use it in GitHub Desktop.
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
### Don't you wish you could use this if-nil idiom? | |
first_name || "Joe" | |
# Well you can't if you expect first_name to be blank instead of nil, so Ruby will short-circuit. | |
# Enter deblank: | |
class Object | |
def deblank | |
self.blank? ? nil : self | |
end | |
end | |
# Now you can do this: | |
first_name.deblank || "Joe" | |
# Instead of this: | |
first_name.blank ? "Joe" : first_name | |
# Probably not really worth the added confusion to other developers however, unless it was in ActiveSupport | |
### Another possibility... | |
class Object | |
def otherwise | |
self.blank? ? yield : self | |
end | |
end | |
# Now you can do this: | |
first_name.otherwise { "Joe" } | |
# Instead of this: | |
first_name.blank ? "Joe" : first_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment