Created
March 11, 2013 17:33
-
-
Save FrancisGX/5136010 to your computer and use it in GitHub Desktop.
Best practice for handling strings like a boss
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
# Notes on the Object#blank?, Object#present?, and Object#presence methods | |
# Calling .present? on an object will return true if the object is not .blank? | |
# Again, for clarity, an object is present if it is not blank. | |
# Thus | |
"".present? # => false | |
# Because | |
"".blank? # => true | |
# And | |
"string".present? # => true | |
# Quite literally, the source for .pressent? | |
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 19 | |
def present? | |
!blank? | |
end | |
# All you need to know is that .present? returns true or false | |
# This allows us to protect against strings that would otherwise error out programs. | |
state = params[:state] if params[:state].present? | |
country = params[:country] if params[:country].present? | |
region = state || country || 'US' | |
# Very useful! | |
# But we can improve this a step further by implementing the .presence method | |
# Calling .presence on an object will return the object itself if it is .present? | |
# Thus | |
"string".presence # => "string" | |
# And | |
"".presence # => nil (which evaluates to false) | |
# So, essentially, .presence returns the object that called it or false | |
# Here's the source. | |
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 37 | |
def presence | |
self if present? | |
end | |
# So our code above could be refactored to | |
region = params[:state].presence || params[:country].presence || 'US' | |
# Pretty significant improvement. | |
# In summation: | |
"".blank? # => true | |
"".present? # => false | |
"".presence # => nil | |
"string".blank? # => false | |
"string".present? # => true | |
"string".presence # => "string" | |
# This can be a powerful tool in learning how to handle empty strings and conditionals. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment