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

Use instance_eval on @tenderlove's suggestion :trollface:

This commit is contained in:
David Heinemeier Hansson 2014-08-29 15:19:32 -07:00
parent cc0d8fbec9
commit 9619450468
3 changed files with 8 additions and 7 deletions

View file

@ -1,6 +1,6 @@
* Added yield to Object#presence, so you can do this: * Added yield to Object#presence, so you can do this:
project.account.owner.presence { |p| p.name.first } || 'Nobody' project.account.owner.presence { name.first } || 'Nobody'
instead of calling twice (which may incur double SQL calls): instead of calling twice (which may incur double SQL calls):

View file

@ -40,15 +40,16 @@ class Object
# 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 # 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 # and the result of that block will then be returned. The block itself is run against
# the instance you're running #presence on (using instance_eval)
# #
# project.account.owner.presence { |p| p.name.first } || 'Nobody' # project.account.owner.presence { name.first } || 'Nobody'
# #
# @return [Object] # @return [Object]
def presence def presence(&block)
if present? if present?
if block_given? if block_given?
yield self instance_eval(&block)
else else
self self
end end

View file

@ -35,7 +35,7 @@ class BlankTest < ActiveSupport::TestCase
end end
def test_presence_with_a_block def test_presence_with_a_block
assert_equal "SALLY", "sally".presence(&:upcase) || "Nobody" assert_equal "SALLY", "sally".presence { upcase } || "Nobody"
assert_equal "Nobody", nil.presence(&:upcase) || "Nobody" assert_equal "Nobody", nil.presence { upcase } || "Nobody"
end end
end end