[ruby-core:98288] [Ruby master Feature#16832] Use #name rather than #inspect to build "uninitialized constant" error messages
From:
daniel@...42.com
Date:
2020-05-12 15:33:23 UTC
List:
ruby-core #98288
Issue #16832 has been updated by Dan0042 (Daniel DeLorme).
+1 for using #name and falling back to #inspect
Rails is correct in extending inspect to return more useful human-readable information, and a NameError should tell you about the problem name (including namespace), not about extra information regarding the module/class to which the namespace resolves. I feel that depending on #inspect to return the name here is a hack.
Ideally the NameError would contain the fully-qualified constant name actually used in the code:
```
class A; end
B = A
B::X #=> NameError (uninitialized constant A::X)
# ideally would say constant B::X
```
but that's getting a bit out of scope for this ticket. #name is the next-best choice.
----------------------------------------
Feature #16832: Use #name rather than #inspect to build "uninitialized constant" error messages
https://bugs.ruby-lang.org/issues/16832#change-85528
* Author: byroot (Jean Boussier)
* Status: Open
* Priority: Normal
----------------------------------------
While debugging a bug in Rails (https://github.com/rails/rails/pull/37632#issuecomment-623387954) I noticed `NameError` calls `inspect` on the `const_get` receiver to build its error message.
The problem is that some libraries such as Active Record have been redefining `inspect` for years to provide human readable information, e.g.:
```
>> Shipit::Stack.inspect
=> "Shipit::Stack (call 'Shipit::Stack.connection' to establish a connection)"
>> Shipit::Stack.connection; nil
>> Shipit::Stack.inspect
=> "Shipit::Stack(id: integer, environment: string, ...)"
```
Which makes for fairly unhelpful error messages:
```
>> Shipit::Stack.const_get(:Foo)
Traceback (most recent call last):
2: from (irb):4
1: from (irb):4:in `const_get'
NameError (uninitialized constant #<Class:0x00007fc8cadf2dd0>::Foo)
```
So perhaps it's Active Record that is at fault here, but from my understanding since the goal is to display the constant path that was requested, `name` is much more likely to return a relevant constant name.
Proposed patch: https://github.com/ruby/ruby/pull/3080
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>