Project

General

Profile

Actions

Bug #11294

closed

Possible bug in Object.const_get

Added by nepalez (Andrew Kozin) over 9 years ago. Updated over 9 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:69704]

Description

module Foo; end
module Foo::Baz; end
module Bar; end
module Bar::Qux; end

Object.const_get "Foo::Baz::Bar::Qux"
# => Bar::Qux

Why on earth it is found at all?
It seems pretty weird to me.

The real problem arises later, when I add Foo::Bar::Qux:

module Foo::Bar; end
module Foo::Bar::Qux; end

then the tree becomes as following:

Foo::Bar::Qux
Foo::Baz
Bar::Qux

But the result remains the same:

Object.const_get "Foo::Baz::Bar::Qux"
# => Bar::Qux

Here I'd expect searching "Foo::Baz::Bar::Qux" to

  • either return nothing (this is less astonished, because there is no such constant),
  • or find the closest Bar::Qux to Foo::Bar, that is Foo::Bar::Qux, not the Bar::Qux

I cannot even understand the logic that follows the Object.const_get in providing such a result.

Updated by nobu (Nobuyoshi Nakada) over 9 years ago

  • Description updated (diff)
  • Status changed from Open to Rejected

Toplevel constants are defined under Object context, which are inherited by every contexts.

Your results are same as:

module Foo::Baz; p Bar::Qux; end #=> Bar::Qux
  • or find the closest Bar::Qux to Foo::Bar, that is Foo::Bar::Qux, not the Bar::Qux

It's not close.
And Foo::Baz::Bar is different from Foo::Bar.

Updated by nepalez (Andrew Kozin) over 9 years ago

Thank you, Nobuyoshi, for your answering. Now I see the reason.

When I told that Foo::Bar::Qux is "closest" to Foo::Baz I meant that in a namespace:

module Foo
  module Baz
    p Bar::Qux
  end
end
# => Foo::Bar::Qux

That's why I think it still be useful to have a "strict" version of Object.const_get that would treat the namespace literally with a syntax of sorts:

Object.const_get "Foo::Baz::Bar::Qux", strict: true
# => NameError: uninitialized constant Foo::Baz::Bar
Actions

Also available in: Atom PDF

Like0
Like0Like0