Added yield to Object#presence

上级 7475b43c
* Added yield to Object#presence, so you can do this:
person.presence { |p| p.name.first } || 'Nobody'
*DHH*
* Fix the `ActiveSupport::Duration#instance_of?` method to return the right * Fix the `ActiveSupport::Duration#instance_of?` method to return the right
value with the class itself since it was previously delegated to the value with the class itself since it was previously delegated to the
internal value. internal value.
......
...@@ -39,9 +39,20 @@ def present? ...@@ -39,9 +39,20 @@ def present?
# #
# region = params[:state].presence || params[:country].presence || 'US' # region = params[:state].presence || params[:country].presence || 'US'
# #
# You can also use this with a block that will be yielded if the object is present
# and the result of that block will then be returned
#
# person.presence { |p| p.name.first } || 'Nobody'
#
# @return [Object] # @return [Object]
def presence def presence
self if present? if present?
if block_given?
yield self
else
self
end
end
end end
end end
......
...@@ -33,4 +33,9 @@ def test_presence ...@@ -33,4 +33,9 @@ def test_presence
BLANK.each { |v| assert_equal nil, v.presence, "#{v.inspect}.presence should return nil" } 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" } NOT.each { |v| assert_equal v, v.presence, "#{v.inspect}.presence should return self" }
end end
def test_presence_with_a_block
assert_equal "SALLY", "sally".presence(&:upcase) || "Nobody"
assert_equal "Nobody", nil.presence(&:upcase) || "Nobody"
end
end end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册