try.rb 1.5 KB
Newer Older
1
class Object
2
  # Invokes the public method identified by the symbol +method+, passing it any arguments
P
Pratik Naik 已提交
3 4
  # and/or the block specified, just like the regular Ruby <tt>Object#send</tt> does.
  #
J
Jeremy Kemper 已提交
5
  # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
P
Pratik Naik 已提交
6
  # and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
7
  #
8 9
  # If try is called without a method to call, it will yield any given block with the object.
  #
10 11
  # ==== Examples
  #
S
Sebastian Martinez 已提交
12
  # Without +try+
13 14 15 16
  #   @person && @person.name
  # or
  #   @person ? @person.name : nil
  #
S
Sebastian Martinez 已提交
17
  # With +try+
18 19
  #   @person.try(:name)
  #
P
Pratik Naik 已提交
20
  # +try+ also accepts arguments and/or a block, for the method it is trying
21 22
  #   Person.try(:find, 1)
  #   @people.try(:collect) {|p| p.name}
23
  #
R
R.T. Lechow 已提交
24
  # Without a method argument try will yield to the block unless the receiver is nil.
25
  #   @person.try { |p| "#{p.first_name} #{p.last_name}" }
26
  #--
V
Vasiliy Ermolovich 已提交
27
  # +try+ behaves like +Object#public_send+, unless called on +NilClass+.
28 29 30 31
  def try(*a, &b)
    if a.empty? && block_given?
      yield self
    else
32
      public_send(*a, &b)
33 34
    end
  end
35 36
end

S
Sebastian Martinez 已提交
37
class NilClass
A
Akira Matsuda 已提交
38
  # Calling +try+ on +nil+ always returns +nil+.
S
Sebastian Martinez 已提交
39
  # It becomes specially helpful when navigating through associations that may return +nil+.
S
Sebastian Martinez 已提交
40 41 42
  #
  # === Examples
  #
S
Sebastian Martinez 已提交
43
  #   nil.try(:name) # => nil
S
Sebastian Martinez 已提交
44
  #
S
Sebastian Martinez 已提交
45 46
  # Without +try+
  #   @person && !@person.children.blank? && @person.children.first.name
S
Sebastian Martinez 已提交
47
  #
S
Sebastian Martinez 已提交
48
  # With +try+
S
Sebastian Martinez 已提交
49
  #   @person.try(:children).try(:first).try(:name)
50 51 52 53
  def try(*args)
    nil
  end
end