From 141d864e0ec1098176141e6cb6aef3eaf07e830f Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 29 Aug 2014 14:58:36 -0700 Subject: [PATCH] Added yield to Object#presence --- activesupport/CHANGELOG.md | 6 ++++++ .../lib/active_support/core_ext/object/blank.rb | 13 ++++++++++++- activesupport/test/core_ext/object/blank_test.rb | 5 +++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index e0d154271f..6830360eba 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -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. diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb index 38e43478df..164a3c47d0 100644 --- a/activesupport/lib/active_support/core_ext/object/blank.rb +++ b/activesupport/lib/active_support/core_ext/object/blank.rb @@ -39,9 +39,20 @@ def present? # # 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 diff --git a/activesupport/test/core_ext/object/blank_test.rb b/activesupport/test/core_ext/object/blank_test.rb index 246bc7fa61..7b3f10b4da 100644 --- a/activesupport/test/core_ext/object/blank_test.rb +++ b/activesupport/test/core_ext/object/blank_test.rb @@ -33,4 +33,9 @@ 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 + + def test_presence_with_a_block + assert_equal "SALLY", "sally".presence(&:upcase) || "Nobody" + assert_equal "Nobody", nil.presence(&:upcase) || "Nobody" + end end -- GitLab