Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 6818

Show
Ignore:
Timestamp:
05/23/07 07:03:31 (1 year ago)
Author:
bitsweat
Message:

whiny nil shouldn't depend on Active Record

Files:

Legend:

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

    r4604 r6818  
    1 # Extensions to nil which allow for more helpful error messages for  
     1# Extensions to nil which allow for more helpful error messages for 
    22# people who are new to rails. 
    33# 
    44# The aim is to ensure that when users pass nil to methods where that isn't 
    55# 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  
     6# by the framework users will see a message explaining what type of object 
    77# was expected. 
    88 
    99class NilClass 
    10   WHINERS = [ ::ActiveRecord::Base, ::Array ] 
    11    
     10  WHINERS = [::Array] 
     11  WHINERS << ::ActiveRecord::Base if defined? ::ActiveRecord 
     12 
    1213  @@method_class_map = Hash.new 
    13    
     14 
    1415  WHINERS.each do |klass| 
    1516    methods = klass.public_instance_methods - public_instance_methods 
    16     methods.each do |method| 
    17       @@method_class_map[method.to_sym] = klass 
    18     end 
     17    class_name = klass.name 
     18    methods.each { |method| @@method_class_map[method.to_sym] = class_name } 
    1919  end 
    20    
     20 
    2121  def id 
    2222    raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller 
     
    2828    end 
    2929 
    30     def raise_nil_warning_for(klass = nil, selector = nil, with_caller = nil) 
     30    def raise_nil_warning_for(class_name = nil, selector = nil, with_caller = nil) 
    3131      message = "You have a nil object when you didn't expect it!" 
    32       message << "\nYou might have expected an instance of #{klass}." if klass 
     32      message << "\nYou might have expected an instance of #{class_name}." if class_name 
    3333      message << "\nThe error occurred while evaluating nil.#{selector}" if selector 
    34        
     34 
    3535      raise NoMethodError, message, with_caller || caller 
    3636    end