New method Object#attempt, similar to Object#try, except returns self instead of nil if method does not exist

16 views
Skip to first unread message

jeffrey....@chargeback.com

unread,
Mar 8, 2017, 4:44:53 PM3/8/17
to Ruby on Rails: Core
I have run into many cases where I need to attempt to run the method, however if the method does not exist, I would prefer to get the object back, instead of nil.

This is the change I am proposing


module ActiveSupport
 
module Tryable #:nodoc:
   
def try(*a, &b)
     
try!(*a, &b) if a.empty? || respond_to?(a.first)
   
end
   
   
# NEW METHOD
   
def attempt(*a, &b)
     
try(*a, &b) || self
   
end
 
end
end

Reply all
Reply to author
Forward
0 new messages