From 0378e2f4a8319440dd65c82b16f189161472d237 Mon Sep 17 00:00:00 2001 From: Ufuk Kayserilioglu Date: Tue, 27 Sep 2022 01:19:22 +0300 Subject: Add Class#attached_object Implements [Feature #12084] Returns the object for which the receiver is the singleton class, or raises TypeError if the receiver is not a singleton class. --- class.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'class.c') diff --git a/class.c b/class.c index 7a32951e60..b0d23153de 100644 --- a/class.c +++ b/class.c @@ -1589,6 +1589,33 @@ rb_class_subclasses(VALUE klass) return class_descendants(klass, true); } +/* + * 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: `Foo' is not a singleton class + * Foo.new.singleton_class.attached_object #=> # + * TrueClass.attached_object #=> TypeError: `TrueClass' is not a singleton class + * NilClass.attached_object #=> TypeError: `NilClass' is not a singleton class + */ + +VALUE +rb_class_attached_object(VALUE klass) +{ + if (!FL_TEST(klass, FL_SINGLETON)) { + rb_raise(rb_eTypeError, "`%"PRIsVALUE"' is not a singleton class", klass); + } + + return rb_attr_get(klass, id_attached); +} + static void ins_methods_push(st_data_t name, st_data_t ary) { -- cgit v1.2.1