Skip to content

Commit 5efe77f

Browse files
committed
Modify class variable definition in singleton class; fix #3539
1 parent 898077a commit 5efe77f

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/variable.c

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -819,12 +819,22 @@ mrb_mod_cv_set(mrb_state *mrb, struct RClass *c, mrb_sym sym, mrb_value v)
819819
c = c->super;
820820
}
821821

822-
if (!cls->iv) {
823-
cls->iv = iv_new(mrb);
822+
if (cls && cls->tt == MRB_TT_SCLASS) {
823+
mrb_value klass;
824+
klass = mrb_obj_iv_get(mrb, (struct RObject*)cls,
825+
mrb_intern_lit(mrb, "__attached__"));
826+
827+
c = mrb_class_ptr(klass);
828+
}else{
829+
c = cls;
830+
}
831+
832+
if (!c->iv) {
833+
c->iv = iv_new(mrb);
824834
}
825835

826-
mrb_write_barrier(mrb, (struct RBasic*)cls);
827-
iv_put(mrb, cls->iv, sym, v);
836+
mrb_write_barrier(mrb, (struct RBasic*)c);
837+
iv_put(mrb, c->iv, sym, v);
828838
}
829839

830840
MRB_API void

test/t/class.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,19 @@ def class_variable
384384
assert_equal("value", ClassVariableTest.class_variable)
385385
end
386386

387+
assert('class variable definition in singleton_class') do
388+
class ClassVariableDefinitionInSingletonTest
389+
class << self
390+
@@class_variable = "value"
391+
end
392+
def class_variable
393+
@@class_variable
394+
end
395+
end
396+
397+
assert_equal("value", ClassVariableDefinitionInSingletonTest.new.class_variable)
398+
end
399+
387400
assert('class variable in module and class << self style class method') do
388401
module ClassVariableInModuleTest
389402
@@class_variable = "value"

0 commit comments

Comments
 (0)