mirror of
https://github.com/github/rails.git
synced 2026-01-24 22:08:15 -05:00
Refactor Object#try to use inheritance. [#1774 state:resolved]
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
This commit is contained in:
@@ -87,21 +87,4 @@ class Object
|
||||
respond_to? "acts_like_#{duck}?"
|
||||
end
|
||||
|
||||
# Tries to send the method only if object responds to it. Return +nil+ otherwise.
|
||||
# It will also forward any arguments and/or block like Object#send does.
|
||||
#
|
||||
# ==== Example :
|
||||
#
|
||||
# # Without try
|
||||
# @person ? @person.name : nil
|
||||
#
|
||||
# With try
|
||||
# @person.try(:name)
|
||||
#
|
||||
# # try also accepts arguments/blocks for the method it is trying
|
||||
# Person.try(:find, 1)
|
||||
# @people.try(:map) {|p| p.name}
|
||||
def try(method, *args, &block)
|
||||
send(method, *args, &block) unless self.nil?
|
||||
end
|
||||
end
|
||||
|
||||
30
activesupport/lib/active_support/core_ext/try.rb
Normal file
30
activesupport/lib/active_support/core_ext/try.rb
Normal file
@@ -0,0 +1,30 @@
|
||||
class Object
|
||||
# Tries to send the method only if object responds to it. Return +nil+ otherwise.
|
||||
# It will also forward any arguments and/or block like Object#send does.
|
||||
#
|
||||
# ==== Examples
|
||||
#
|
||||
# Without try
|
||||
# @person && @person.name
|
||||
# or
|
||||
# @person ? @person.name : nil
|
||||
#
|
||||
# With try
|
||||
# @person.try(:name)
|
||||
#
|
||||
# Try also accepts arguments/blocks for the method it is trying
|
||||
# Person.try(:find, 1)
|
||||
# @people.try(:collect) {|p| p.name}
|
||||
#--
|
||||
# This method def is for rdoc only. The alias_method below overrides it as an optimization.
|
||||
def try(method, *args, &block)
|
||||
send(method, *args, &block)
|
||||
end
|
||||
alias_method :try, :__send__
|
||||
end
|
||||
|
||||
class NilClass
|
||||
def try(*args)
|
||||
nil
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user