1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Added yield to Object#presence

This commit is contained in:
David Heinemeier Hansson 2014-08-29 14:58:36 -07:00
parent 7475b43cdb
commit 141d864e0e
3 changed files with 23 additions and 1 deletions

View file

@ -1,3 +1,9 @@
* 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
value with the class itself since it was previously delegated to the
internal value.

View file

@ -39,9 +39,20 @@ class Object
#
# 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]
def presence
self if present?
if present?
if block_given?
yield self
else
self
end
end
end
end

View file

@ -33,4 +33,9 @@ class BlankTest < ActiveSupport::TestCase
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
def test_presence_with_a_block
assert_equal "SALLY", "sally".presence(&:upcase) || "Nobody"
assert_equal "Nobody", nil.presence(&:upcase) || "Nobody"
end
end