Lots going on
[lyrix.git] / vendor / rails / activesupport / lib / active_support / whiny_nil.rb
blobf614b41fc76cdd939394711b507f394f6d7d2e56
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
7 # was expected.
9 class NilClass
10   WHINERS = [::Array]
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 }
19   end
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
25   private
26     def method_missing(method, *args, &block)
27       raise_nil_warning_for @@method_class_map[method], method, caller
28     end
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
36     end
37 end