1 # Extensions to nil which allow for more helpful error messages for
2 # people who are new to rails.
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
11 WHINERS << ::ActiveRecord::Base if defined? ::ActiveRecord
13 @@method_class_map = Hash.new
15 WHINERS.each do |klass|
16 methods = klass.public_instance_methods - public_instance_methods
17 class_name = klass.name
18 methods.each { |method| @@method_class_map[method.to_sym] = class_name }
22 raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller
26 def method_missing(method, *args, &block)
27 raise_nil_warning_for @@method_class_map[method], method, caller
30 def raise_nil_warning_for(class_name = 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 #{class_name}." if class_name
33 message << "\nThe error occurred while evaluating nil.#{selector}" if selector
35 raise NoMethodError, message, with_caller || caller