2007-05-23 03:03:31 -04:00
|
|
|
# Extensions to nil which allow for more helpful error messages for
|
2005-06-20 07:15:46 -04:00
|
|
|
# people who are new to rails.
|
|
|
|
#
|
|
|
|
# The aim is to ensure that when users pass nil to methods where that isn't
|
|
|
|
# appropriate, instead of NoMethodError and the name of some method used
|
2007-05-23 03:03:31 -04:00
|
|
|
# by the framework users will see a message explaining what type of object
|
2005-06-20 07:15:46 -04:00
|
|
|
# was expected.
|
|
|
|
|
|
|
|
class NilClass
|
2007-05-23 03:03:31 -04:00
|
|
|
WHINERS = [::Array]
|
|
|
|
WHINERS << ::ActiveRecord::Base if defined? ::ActiveRecord
|
|
|
|
|
2005-06-20 07:15:46 -04:00
|
|
|
@@method_class_map = Hash.new
|
2007-05-23 03:03:31 -04:00
|
|
|
|
2005-06-20 07:15:46 -04:00
|
|
|
WHINERS.each do |klass|
|
|
|
|
methods = klass.public_instance_methods - public_instance_methods
|
2007-05-23 03:03:31 -04:00
|
|
|
class_name = klass.name
|
|
|
|
methods.each { |method| @@method_class_map[method.to_sym] = class_name }
|
2005-06-20 07:15:46 -04:00
|
|
|
end
|
2007-05-23 03:03:31 -04:00
|
|
|
|
2005-06-21 12:36:40 -04:00
|
|
|
def id
|
2005-07-04 05:54:30 -04:00
|
|
|
raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller
|
2005-06-21 12:36:40 -04:00
|
|
|
end
|
2005-06-20 07:15:46 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
def method_missing(method, *args, &block)
|
2005-10-14 22:24:05 -04:00
|
|
|
raise_nil_warning_for @@method_class_map[method], method, caller
|
2005-06-20 07:15:46 -04:00
|
|
|
end
|
|
|
|
|
2007-05-23 03:03:31 -04:00
|
|
|
def raise_nil_warning_for(class_name = nil, selector = nil, with_caller = nil)
|
2005-10-14 22:24:05 -04:00
|
|
|
message = "You have a nil object when you didn't expect it!"
|
2007-05-23 03:03:31 -04:00
|
|
|
message << "\nYou might have expected an instance of #{class_name}." if class_name
|
2006-07-10 15:41:59 -04:00
|
|
|
message << "\nThe error occurred while evaluating nil.#{selector}" if selector
|
2007-05-23 03:03:31 -04:00
|
|
|
|
2005-10-14 22:24:05 -04:00
|
|
|
raise NoMethodError, message, with_caller || caller
|
2005-06-20 07:15:46 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|