Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source
Show
Ignore:
Timestamp:
04/05/08 03:52:58 (5 months ago)
Author:
pratik
Message:

Improve documentation.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activesupport/lib/active_support/whiny_nil.rb

    r9093 r9226  
    1 # Extensions to nil which allow for more helpful error messages for 
    2 # people who are new to rails. 
     1# Extensions to +nil+ which allow for more helpful error messages for people who 
     2# are new to Rails. 
    33# 
    4 # The aim is to ensure that when users pass nil to methods where that isn't 
    5 # appropriate, instead of NoMethodError and the name of some method used 
    6 # by the framework users will see a message explaining what type of object 
    7 # was expected. 
    8  
     4# Ruby raises NoMethodError if you invoke a method on an object that does not 
     5# respond to it: 
     6
     7#   $ ruby -e nil.destroy 
     8#   -e:1: undefined method `destroy' for nil:NilClass (NoMethodError) 
     9
     10# With these extensions, if the method belongs to the public interface of the 
     11# classes in NilClass::WHINERS the error message suggests which could be the 
     12# actual intended class: 
     13
     14#   $ script/runner nil.destroy  
     15#   ... 
     16#   You might have expected an instance of ActiveRecord::Base. 
     17#   ... 
     18
     19# NilClass#id exists in Ruby 1.8 (though it is deprecated). Since +id+ is a fundamental 
     20# method of Active Record models NilClass#id is redefined as well to raise a RuntimeError 
     21# and warn the user. She probably wanted a model database identifier and the 4 
     22# returned by the original method could result in obscure bugs. 
     23
     24# The flag <tt>config.whiny_nils</tt> determines whether this feature is enabled. 
     25# By default it is on in development and test modes, and it is off in production 
     26# mode. 
    927class NilClass 
    1028  WHINERS = [::Array] 
     
    1937  end 
    2038 
    21   # Raises a RuntimeError when you attempt to call id on nil or a nil object
     39  # Raises a RuntimeError when you attempt to call +id+ on +nil+
    2240  def id 
    2341    raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller 
     
    2947    end 
    3048 
    31     # Raises a NoMethodError when you attempt to call a method on nil, or a nil object
     49    # Raises a NoMethodError when you attempt to call a method on +nil+
    3250    def raise_nil_warning_for(class_name = nil, selector = nil, with_caller = nil) 
    3351      message = "You have a nil object when you didn't expect it!"