Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added Object#presence that returns the object if it's #present? other…

…wise returns nil [DHH/Colin Kelley]
  • Loading branch information...
commit 1668ad3baf36aa1fd495e7229c46ebbdebdffd27 1 parent 1f44fc9
David Heinemeier Hansson dhh authored jeremy committed
2  activesupport/CHANGELOG
View
@@ -1,5 +1,7 @@
*2.3.6 (pending)*
+* Added Object#presence that returns the object if it's #present? otherwise returns nil [DHH/Colin Kelley]
+
* New assertions assert_blank and assert_present. #4299 [Juanjo Bazan]
* Use Object#singleton_class instead of #metaclass. Prefer Ruby's choice. [Jeremy Kemper]
22 activesupport/lib/active_support/core_ext/object/blank.rb
View
@@ -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 @@ def blank?
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:
9 activesupport/test/core_ext/blank_test.rb
View
@@ -5,12 +5,17 @@ class BlankTest < Test::Unit::TestCase
NOT = [ EmptyFalse.new, Object.new, true, 0, 1, 'a', [nil], { nil => 0 } ]
def test_blank
- BLANK.each { |v| assert v.blank?, "#{v.inspect} should be blank" }
+ BLANK.each { |v| assert v.blank?, "#{v.inspect} should be blank" }
NOT.each { |v| assert !v.blank?, "#{v.inspect} should not be blank" }
end
def test_present
BLANK.each { |v| assert !v.present?, "#{v.inspect} should not be present" }
- NOT.each { |v| assert v.present?, "#{v.inspect} should be present" }
+ NOT.each { |v| assert v.present?, "#{v.inspect} should be present" }
+ end
+
+ def test_presence
+ BLANK.each { |v| assert_equal nil, v.presence, "#{v.inspect}.presence should return nil" }
+ NOT.each { |v| assert_equal v, v.presence, "#{v.inspect}.presence should return self" }
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.