blob: 0dccd40c55f8f35811f7d14706a9edd27bb16294 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
|