diff options
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object/try.rb')
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/try.rb | 18 |
1 files changed, 15 insertions, 3 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb index 04619124a1..e77a9da0ec 100644 --- a/activesupport/lib/active_support/core_ext/object/try.rb +++ b/activesupport/lib/active_support/core_ext/object/try.rb @@ -9,12 +9,12 @@ class Object # # ==== Examples # - # Without try + # Without +try+ # @person && @person.name # or # @person ? @person.name : nil # - # With try + # With +try+ # @person.try(:name) # # +try+ also accepts arguments and/or a block, for the method it is trying @@ -34,7 +34,19 @@ class Object end end -class NilClass #:nodoc: +class NilClass + # Calling +try+ on +nil+ always returns +nil+. + # It becomes specially helpful when navigating through associations that may return +nil+. + # + # === Examples + # + # nil.try(:name) # => nil + # + # Without +try+ + # @person && !@person.children.blank? && @person.children.first.name + # + # With +try+ + # @person.try(:children).try(:first).try(:name) def try(*args) nil end |