Changeset 6818
- Timestamp:
- 05/23/07 07:03:31 (1 year ago)
- 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 2 2 # people who are new to rails. 3 3 # 4 4 # The aim is to ensure that when users pass nil to methods where that isn't 5 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 6 # by the framework users will see a message explaining what type of object 7 7 # was expected. 8 8 9 9 class NilClass 10 WHINERS = [ ::ActiveRecord::Base, ::Array ] 11 10 WHINERS = [::Array] 11 WHINERS << ::ActiveRecord::Base if defined? ::ActiveRecord 12 12 13 @@method_class_map = Hash.new 13 14 14 15 WHINERS.each do |klass| 15 16 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 } 19 19 end 20 20 21 21 def id 22 22 raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller … … 28 28 end 29 29 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) 31 31 message = "You have a nil object when you didn't expect it!" 32 message << "\nYou might have expected an instance of #{ klass}." if klass32 message << "\nYou might have expected an instance of #{class_name}." if class_name 33 33 message << "\nThe error occurred while evaluating nil.#{selector}" if selector 34 34 35 35 raise NoMethodError, message, with_caller || caller 36 36 end