From 5e51bdda59c9ba8e5faf86294e3e431bd45f1830 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 29 Aug 2014 15:32:24 -0700 Subject: We tenderized the wrong method! Object#try already had the yield option, just needed some tenderloving instance_eval to fit the bill --- .../lib/active_support/core_ext/object/blank.rb | 16 ++-------------- activesupport/lib/active_support/core_ext/object/try.rb | 11 ++++++++++- 2 files changed, 12 insertions(+), 15 deletions(-) (limited to 'activesupport/lib') diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb index 99fd22ff56..38e43478df 100644 --- a/activesupport/lib/active_support/core_ext/object/blank.rb +++ b/activesupport/lib/active_support/core_ext/object/blank.rb @@ -39,21 +39,9 @@ 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. The block itself is run against - # the instance you're running #presence on (using instance_eval) - # - # project.account.owner.presence { name.first } || 'Nobody' - # # @return [Object] - def presence(&block) - if present? - if block_given? - instance_eval(&block) - else - self - end - end + def presence + self if present? end end diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb index 48190e1e66..31919474ed 100644 --- a/activesupport/lib/active_support/core_ext/object/try.rb +++ b/activesupport/lib/active_support/core_ext/object/try.rb @@ -33,6 +33,11 @@ class Object # ... # end # + # You can also call try with a block without accepting an argument, and the block + # will be instance_eval'ed instead: + # + # @person.try { upcase.truncate(50) } + # # Please also note that +try+ is defined on +Object+, therefore it won't work # with instances of classes that do not have +Object+ among their ancestors, # like direct subclasses of +BasicObject+. For example, using +try+ with @@ -40,7 +45,11 @@ class Object # delegator itself. def try(*a, &b) if a.empty? && block_given? - yield self + if b.arity.zero? + instance_eval(&b) + else + yield self + end else public_send(*a, &b) if respond_to?(a.first) end -- cgit v1.2.3