Prev | Current Page 90 | Next

Brad Ediger

"Advanced Rails"

They are designed to
help trap unexpected nil values as early as possible, and to provide more sensible error
messages to the developer when nil is encountered.
Without these extensions, calling one of Array??™s instance methods on an object that
happened to be nil would generate a standard NoMethodError if NilClass did not also
contain the method. This could be frustrating to track down, especially if the method was
called from deep in the framework.
Whiny Nil intercepts those NoMethodErrors with method_missing and makes a suggestion
about the type of object the developer may have been expecting (either Array or
ActiveRecord::Base), based on the name of the method called.
nil.sort
# !> NoMethodError: You have a nil object when you didn't expect it!
# !> You might have expected an instance of Array.
nil.save
# !> NoMethodError: You have a nil object when you didn't expect it!
# !> You might have expected an instance of ActiveRecord::Base.
The Whiny Nil extensions also redefine NilClass#id, which raises an error. Without this
extension, nil.id would return 4 (Ruby??™s immediate representation of nil, the same as
nil.object_id). This would be confusing when chaining methods together. Under the
Whiny Nil system, this raises a more informative exception:
nil.id
# !> RuntimeError: Called id for nil, which would mistakenly be 4 --
# !> if you really wanted the id of nil, use object_id
The Whiny Nil system can be turned off in the Rails configuration by setting config.


Pages:
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102