Skip to content

Commit e89eecc

Browse files
committed
No need to call rb_define_class/module_under_id
Classes/modules defined in a namespace are defined under ::Object as usual (as without namespaces), and it'll be set into the const_tbl of ::Object. In namespaces, namespace objects' const_tbl is equal to the one of ::Object. So constants of ::Object are just equal to constants of the namespace. That means, top level classes/modules in a namespace can be referred as namespace::KlassName without calling rb_define_class_under_id().
1 parent bc77a11 commit e89eecc

File tree

2 files changed

+6
-12
lines changed

2 files changed

+6
-12
lines changed

class.c

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1605,13 +1605,8 @@ VALUE
16051605
rb_define_class(const char *name, VALUE super)
16061606
{
16071607
VALUE klass;
1608-
ID id;
1609-
const rb_namespace_t *ns = rb_current_namespace();
1608+
ID id = rb_intern(name);
16101609

1611-
id = rb_intern(name);
1612-
if (NAMESPACE_OPTIONAL_P(ns)) {
1613-
return rb_define_class_id_under(ns->ns_object, id, super);
1614-
}
16151610
if (rb_const_defined(rb_cObject, id)) {
16161611
klass = rb_const_get(rb_cObject, id);
16171612
if (!RB_TYPE_P(klass, T_CLASS)) {
@@ -1723,13 +1718,8 @@ VALUE
17231718
rb_define_module(const char *name)
17241719
{
17251720
VALUE module;
1726-
ID id;
1727-
const rb_namespace_t *ns = rb_current_namespace();
1721+
ID id = rb_intern(name);
17281722

1729-
id = rb_intern(name);
1730-
if (NAMESPACE_OPTIONAL_P(ns)) {
1731-
return rb_define_module_id_under(ns->ns_object, id);
1732-
}
17331723
if (rb_const_defined(rb_cObject, id)) {
17341724
module = rb_const_get(rb_cObject, id);
17351725
if (!RB_TYPE_P(module, T_MODULE)) {

test/ruby/test_namespace.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -715,6 +715,7 @@ def self.ns6_proc = ->(){ Namespace.current }
715715
def self.yield_block = yield
716716
def self.call_block(&b) = b.call
717717
end
718+
FOO_NAME = Foo.name
718719
NS9 = Foo.new.ns4
719720
EOC
720721
ns.eval(code)
@@ -731,6 +732,9 @@ def self.call_block(&b) = b.call
731732
assert_equal outer, ns::Foo.yield_block{ Namespace.current } # method yields
732733
assert_equal outer, ns::Foo.call_block{ Namespace.current } # method calls a block
733734
assert_equal ns, ns::NS9 # on TOP frame, referring a class in the current
735+
736+
assert_equal "Foo", ns::FOO_NAME
737+
assert_equal "Foo", ns::Foo.name
734738
end;
735739
end
736740

0 commit comments

Comments
 (0)