mruby-class-ext: new method `attached_object` introduced in Ruby3.2
MODIFY
mrbgems/mruby-class-ext/src/class.c
mrbgems/mruby-class-ext/src/class.c
#include "mruby/string.h"
#include "mruby/array.h"
#include "mruby/proc.h"
+#include "mruby/variable.h"
+#include "mruby/presym.h"
static mrb_value
mrb_mod_name(mrb_state *mrb, mrb_value self)
@@ -108,6 +110,33 @@ mrb_class_subclasses(mrb_state *mrb, mrb_value self)
return ary;
}
+/*
+ * call-seq:
+ * attached_object -> object
+ *
+ * Returns the object for which the receiver is the singleton class.
+ * Raises an TypeError if the class is not a singleton class.
+ *
+ * class Foo; end
+ *
+ * Foo.singleton_class.attached_object #=> Foo
+ * Foo.attached_object #=> TypeError: not a singleton class
+ * Foo.new.singleton_class.attached_object #=> #<Foo:0x000000010491a370>
+ * TrueClass.attached_object #=> TypeError: not a singleton class
+ * NilClass.attached_object #=> TypeError: not a singleton class
+ */
+static mrb_value
+mrb_class_attached_object(mrb_state *mrb, mrb_value self)
+{
+ struct RClass *c;
+
+ c = mrb_class_ptr(self);
+ if (c->tt != MRB_TT_SCLASS) {
+ mrb_raise(mrb, E_TYPE_ERROR, "not a singleton class");
+ }
+ return mrb_obj_iv_get(mrb, (struct RObject*)c, MRB_SYM(__attached__));
+}
+
void
mrb_mruby_class_ext_gem_init(mrb_state *mrb)
{
@@ -120,6 +149,7 @@ mrb_mruby_class_ext_gem_init(mrb_state *mrb)
struct RClass *cls = mrb->class_class;
mrb_define_method(mrb, cls, "subclasses", mrb_class_subclasses, MRB_ARGS_NONE());
+ mrb_define_method(mrb, cls, "attached_object", mrb_class_attached_object, MRB_ARGS_NONE());
}
void

MODIFY
mrbgems/mruby-class-ext/test/class.rb
mrbgems/mruby-class-ext/test/class.rb
@@ -11,3 +11,19 @@ assert 'Class#subclasses' do
assert_equal([c], b.subclasses)
assert_equal([], c.subclasses)
end
+
+assert 'Class#attached_object' do
+ foo = Class.new
+ foo_s = class <<foo
+ foo_s = self
+ end
+ assert_equal(foo, foo_s.attached_object)
+ fooi = foo.new
+ fooi_s = class <<fooi
+ fooi_s = self
+ end
+ assert_equal(fooi, fooi_s.attached_object)
+ assert_raise(TypeError){foo.attached_object}
+ assert_raise(TypeError){TrueClass.attached_object}
+ assert_raise(TypeError){NilClass.attached_object}
+end

mruby-class-ext: new method `attached_object` introduced in Ruby3.2