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

root/branches/1-2-stable/activesupport/lib/active_support/whiny_nil.rb

Revision 4604, 1.3 kB (checked in by bitsweat, 3 years ago)

occured -> occurred. Closes #5559.

Line 
1 # Extensions to nil which allow for more helpful error messages for
2 # people who are new to rails.
3 #
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
9 class NilClass
10   WHINERS = [ ::ActiveRecord::Base, ::Array ]
11  
12   @@method_class_map = Hash.new
13  
14   WHINERS.each do |klass|
15     methods = klass.public_instance_methods - public_instance_methods
16     methods.each do |method|
17       @@method_class_map[method.to_sym] = klass
18     end
19   end
20  
21   def id
22     raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller
23   end
24
25   private
26     def method_missing(method, *args, &block)
27       raise_nil_warning_for @@method_class_map[method], method, caller
28     end
29
30     def raise_nil_warning_for(klass = nil, selector = nil, with_caller = nil)
31       message = "You have a nil object when you didn't expect it!"
32       message << "\nYou might have expected an instance of #{klass}." if klass
33       message << "\nThe error occurred while evaluating nil.#{selector}" if selector
34      
35       raise NoMethodError, message, with_caller || caller
36     end
37 end
38
Note: See TracBrowser for help on using the browser.