From f4da98bf5f5026594c210c77286bad4fb9a64a93 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Fri, 19 Feb 2016 12:05:27 -0800 Subject: [PATCH] Allow clone to take a second argument passed to initialize_clone --- object.c | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/object.c b/object.c index 2497043..e71e0b1 100644 --- a/object.c +++ b/object.c @@ -299,7 +299,7 @@ init_copy(VALUE dest, VALUE obj) /* * call-seq: - * obj.clone -> an_object + * obj.clone(other=nil) -> an_object * * Produces a shallow copy of obj---the instance variables of * obj are copied, but not the objects they reference. @@ -316,13 +316,17 @@ init_copy(VALUE dest, VALUE obj) * s1.inspect #=> "#" * s2.inspect #=> "#" * + * You can provide another object to this method, which +initialize_clone+ + * will be called with in addition to the object's clone, before the object's + * object is frozen. + * * This method may have class-specific behavior. If so, that * behavior will be documented under the #+initialize_copy+ method of * the class. */ -VALUE -rb_obj_clone(VALUE obj) +static VALUE +rb_obj_clone2(int argc, VALUE *argv, VALUE obj) { VALUE clone; VALUE singleton; @@ -341,12 +345,23 @@ rb_obj_clone(VALUE obj) } init_copy(clone, obj); - rb_funcall(clone, id_init_clone, 1, obj); + rb_check_arity(argc, 0, 1); + if (argc == 0) { + rb_funcall(clone, id_init_clone, 1, obj); + } else { + rb_funcall(clone, id_init_clone, 2, obj, argv[0]); + } RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE; return clone; } +VALUE +rb_obj_clone(VALUE obj) +{ + return rb_obj_clone2(0, NULL, obj); +} + /* * call-seq: * obj.dup -> an_object @@ -3424,7 +3439,7 @@ InitVM_Object(void) rb_define_method(rb_mKernel, "class", rb_obj_class, 0); rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0); - rb_define_method(rb_mKernel, "clone", rb_obj_clone, 0); + rb_define_method(rb_mKernel, "clone", rb_obj_clone2, -1); rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0); rb_define_method(rb_mKernel, "itself", rb_obj_itself, 0); rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1); -- 2.7.0