Extract methods in a class to mixin?

F

Florian Frank

Hello all,

I just tried to extract the methods defined in a class and make a mixin
of them. My code looked like this:

class Class

def mixin(*methods)
klass = self
methods.empty? and methods = klass.instance_methods(false)
m = Module.new
m.instance_eval do
methods.each do |s|
define_method(s, klass.instance_method(s))
end
end
m
end

end

class A < Array
def foo; "foo"; end
def bar; "bar"; end
end
class B
end

Mixin1 = A.mixin:)foo)
class B
include Mixin1
end
p B.new.foo

Mixin2 = A.mixin
class C
include Mixin2
end
c = C.new
p c.foo
p c.bar

It failed with a type error "bind argument must be an instance of A". I
don't see why it must be such an instance, because I think this should
be a job for duck typing to find out if messages fail, that are sent in
the method body. So i patched eval.c to stop complaining and it worked.
Perhaps I am missing something: But is there a reason for this check or
could it be deleted in eval.c to allow this behaviour?

Index: eval.c
===================================================================
RCS file: /src/ruby/eval.c,v
retrieving revision 1.531
diff -u -p -r1.531 eval.c
--- eval.c 5 Sep 2003 05:07:54 -0000 1.531
+++ eval.c 8 Sep 2003 12:33:40 -0000
@@ -7438,10 +7438,6 @@ umethod_bind(method, recv)
st_lookup(RCLASS(CLASS_OF(recv))->m_tbl, data->oid, 0)) {
rb_raise(rb_eTypeError, "method `%s' overridden",
rb_id2name(data->oid));
}
- if(!rb_obj_is_kind_of(recv, data->rklass)) {
- rb_raise(rb_eTypeError, "bind argument must be an instance of %s",
- rb_class2name(data->rklass));
- }
}

method = Data_Make_Struct(rb_cMethod,struct METHOD,bm_mark,free,bound);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top