Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, why aren't variable names in the stack trace?

In a rails app with associations (Such as Post belongs_to user), a common exception is this:

NoMethodError: undefined method `user' for nil:NilClass

Ubiquitously, this causes beginners to believe that user is nil. Why don't we have more intuitive errors, such as the following?

NoMethodError: `@post' is a nil:NilClass and doesn't have the method `user'

EDIT: Why is this being downvoted? The question is legitimate. I'd like to know if there is a technical reason preventing this.

like image 938
Peter Ehrlich Avatar asked Jan 22 '26 21:01

Peter Ehrlich


1 Answers

First of all, I disagree with the original assertion. The message clearly says that user is an undefined method, not a variable or a value. I'm not sure how someone could think user is a variable based on this message.

However the answer to your question is that by the time the "user" method is called, the target object has already been loaded from whatever variable referenced it. The call logic for invoking "user" doesn't know anything about where that object came from. It could have been a local variable, an instance variable, a constant...there's no way to tell. Also, the Rails "whiny nil" logic happens in a method_missing implementation, far, far away from the original access of the object; the context of the original variable lookup is not even in scope anymore.

like image 189
Charles Oliver Nutter Avatar answered Jan 24 '26 13:01

Charles Oliver Nutter