aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/object/blank.rb
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2009-12-27 17:54:43 -0800
committerDavid Heinemeier Hansson <david@loudthinking.com>2009-12-27 17:54:43 -0800
commit1c47d04ea5ac19601b316daf8fdc6f38c50eec73 (patch)
treef014e4d006cc02aa06e4c75f365723fe5f6672a3 /activesupport/lib/active_support/core_ext/object/blank.rb
parenta642edbef31fe96fad488accf0052653c573e8db (diff)
downloadrails-1c47d04ea5ac19601b316daf8fdc6f38c50eec73.tar.gz
rails-1c47d04ea5ac19601b316daf8fdc6f38c50eec73.tar.bz2
rails-1c47d04ea5ac19601b316daf8fdc6f38c50eec73.zip
Added Object#presence that returns the object if it's #present? otherwise returns nil [DHH/Colin Kelley]
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object/blank.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/object/blank.rb22
1 files changed, 20 insertions, 2 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb
index 9a1f663bf3..eb99bb1a36 100644
--- a/activesupport/lib/active_support/core_ext/object/blank.rb
+++ b/activesupport/lib/active_support/core_ext/object/blank.rb
@@ -2,11 +2,11 @@ class Object
# An object is blank if it's false, empty, or a whitespace string.
# For example, "", " ", +nil+, [], and {} are blank.
#
- # This simplifies
+ # This simplifies:
#
# if !address.nil? && !address.empty?
#
- # to
+ # ...to:
#
# if !address.blank?
def blank?
@@ -17,6 +17,24 @@ class Object
def present?
!blank?
end
+
+ # Returns object if it's #present? otherwise returns nil.
+ # object.presence is equivalent to object.present? ? object : nil.
+ #
+ # This is handy for any representation of objects where blank is the same
+ # as not present at all. For example, this simplifies a common check for
+ # HTTP POST/query parameters:
+ #
+ # state = params[:state] if params[:state].present?
+ # country = params[:country] if params[:country].present?
+ # region = state || country || 'US'
+ #
+ # ...becomes:
+ #
+ # region = params[:state].presence || params[:country].presence || 'US'
+ def presence
+ self if present?
+ end
end
class NilClass #:nodoc: