Jano Svitok
10/26/2006 11:38:00 AM
On 10/26/06, Victor 'Zverok' Shepelev <vshepelev@imho.com.ua> wrote:
> Jan Svitok (jan.svitok@gmail.com)
> 26/10/2006 13:56:01
>
> > On 10/26/06, Victor 'Zverok' Shepelev <vshepelev@imho.com.ua> wrote:
> > > For some reasons I extensively use this technique:
> > >
> > > obj = MyClass.new(...)
> > > obj.instance_eval{
> > > def my_cool_method
> > > end
> > > }
> > >
> > > #create 1000 clones of the obj, call #my_cool_method
> > > (1..1000).collect{
> > > clon = obj.clone
> > > clon.my_cool_method
> > > }
> > >
> > > The problem is ruby-prof shows each clone's #my_cool_method as separate
> > > one in the report, so I see 1000 lines with 1 calls of #my_cool_method
> > > instead of 1 line with 1000 calls. Is it bug or by design? May this
> > > problem be result of the fact I use latest Ruby 1.9 version?
> >
> > This is what I've found in the sources:
> > My_cool_method is a singleton instance method (not an ordinary
> > instance method). singleton methods are cloned by creating proxy
> > method, so they are not identical.
> >
>
> OK, I've got it.
> Thanks.
>
> > IMHO the most simple way is to define normal instance methods via
> >
> > obj.class.module_eval, i.e. MyClass.module_eval.
>
> Not for me, unfortunately :(
> One of reasons, why I use those strange techniques, is to have different sets of methods in different sets of objects of same class.
>
> More specially, all those objects are HTML DOM nodes, and I want to have #cell(col, row) method for <table> node, #click method for <button> node and even more special cases, like have some special methods for <table class=grid>. My approach is on-the-fly per-CSS-selector extending of certain nodes, and it works well, except for profiling :(
>
> The issue still open.
Maybe you can create new subclasses instead:
my_new_class = Class.new(MyClass)
my_new_class.module_eval {...}
and optionally
Object.const_set(my_new_class_name, mynewclass)
NB: class_eval is an alias for module_eval.