Added Object#presence that returns the object if it's #present? otherwise returns nil [DHH/Colin Kelley]
This commit is contained in:
parent
a642edbef3
commit
1c47d04ea5
@ -1,5 +1,7 @@
|
||||
*Edge*
|
||||
|
||||
* Added Object#presence that returns the object if it's #present? otherwise returns nil [DHH/Colin Kelley]
|
||||
|
||||
* Add Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?/else calls [DHH]
|
||||
|
||||
* Update Edinburgh TimeZone to use "Europe/London" instead of "Europe/Dublin" #3310 [Phil Ross]
|
||||
|
@ -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:
|
||||
|
@ -14,12 +14,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
|
||||
|
Loading…
Reference in New Issue
Block a user