try.rb 1.9 KB
Newer Older
1
class Object
2
  # Invokes the public method identified by the symbol +method+, passing it any arguments
3
  # and/or the block specified, just like the regular Ruby <tt>Object#public_send</tt> does.
P
Pratik Naik 已提交
4
  #
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 10
  # This is also true if the receiving object does not implemented the tried method. It will
  # return +nil+ in that case as well.
  #
11 12
  # If try is called without a method to call, it will yield any given block with the object.
  #
13 14 15 16
  # Please also note that +try+ is defined on +Object+, therefore it won't work with
  # subclasses of +BasicObject+. For example, using try with +SimpleDelegator+ will
  # delegate +try+ to target instead of calling it on delegator itself.
  #
S
Sebastian Martinez 已提交
17
  # Without +try+
18 19 20 21
  #   @person && @person.name
  # or
  #   @person ? @person.name : nil
  #
S
Sebastian Martinez 已提交
22
  # With +try+
23 24
  #   @person.try(:name)
  #
P
Pratik Naik 已提交
25
  # +try+ also accepts arguments and/or a block, for the method it is trying
26 27
  #   Person.try(:find, 1)
  #   @people.try(:collect) {|p| p.name}
28
  #
R
R.T. Lechow 已提交
29
  # Without a method argument try will yield to the block unless the receiver is nil.
30
  #   @person.try { |p| "#{p.first_name} #{p.last_name}" }
31
  #
V
Vasiliy Ermolovich 已提交
32
  # +try+ behaves like +Object#public_send+, unless called on +NilClass+.
33 34 35 36
  def try(*a, &b)
    if a.empty? && block_given?
      yield self
    else
37
      public_send(*a, &b) if respond_to?(a.first)
38 39
    end
  end
40 41
end

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