File: active_support/core_ext/try.rb

Overview
Module Structure
Class Hierarchy
Code

Overview

Module Structure

  module: <Toplevel Module>
  module: <Built-in Module>
  class: NilClass#32
inherits from
  Object ( Builtin-Module )
has properties
method: try / 1 #33

Class Hierarchy

Object ( Builtin-Module )
  NilClass    #32

Code

   1  class Object
   2    # Invokes the method identified by the symbol +method+, passing it any arguments 
   3    # and/or the block specified, just like the regular Ruby <tt>Object#send</tt> does.
   4    #
   5    # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised 
   6    # and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
   7    #
   8    # ==== Examples
   9    #
  10    # Without try
  11    #   @person && @person.name
  12    # or
  13    #   @person ? @person.name : nil
  14    #
  15    # With try
  16    #   @person.try(:name)
  17    #
  18    # +try+ also accepts arguments and/or a block, for the method it is trying
  19    #   Person.try(:find, 1)
  20    #   @people.try(:collect) {|p| p.name}
  21    #--
  22    # This method definition below is for rdoc purposes only. The alias_method call 
  23    # below overrides it as an optimization since +try+ behaves like +Object#send+,
  24    # unless called on +NilClass+.
  25    def try(method, *args, &block)
  26      send(method, *args, &block)
  27    end
  28    remove_method :try
  29    alias_method :try, :__send__
  30  end
  31 
  32  class NilClass
  33    def try(*args)
  34      nil
  35    end
  36  end