Klass.include vs instance.extend question


#1

i want a few instance methods to be automatically defined for the user
without any explicit coding on their part.

in the below distillation of my code, i have two options (labelled), my
question
is whether one option is better in any way than the other, and why one
would prefer one over the other. my suspicion is that option 1 is more
space efficient, and option 2 more time efficient, is that correct?

also i should note that for people to use my module M they must call
(for other reasons) extend, foo, and init_m in the extended class
regardless of which option i finally choose. also the method init_m must
be defined in the manner below (define_method) regardless of the option
i choose, also for other reasons. and so you should not take any of
their having to be there or not into account in your assesment. thanks
many.

module InstanceMethods

instance methods in here

end

module M

option 1

def self.extend_object klass
klass.class_eval ‘include InstanceMethods’
super
end

option 2

def foo
define_method :init_m do
self.extend InstanceMethods
end
end

end

class X
extend M
foo
def intialize
init_m
end
end


#2

2006/5/3, polypus removed_email_address@domain.invalid:

also i should note that for people to use my module M they must call

end

end
Why can’t you just do

class X
include InstanceMethods
end

Did I miss something?

robert


#3

Did I miss something?

ok forget all of my above code. i’ve solved that problem in another
thread, see ‘mixin puzzle’.

but i would still like to know when one would prefer extending the
individual objects instead of ‘including’ into their class (and vice
versa), and what the pros and cons of each method are.

thanks,
_c


#4

2006/5/6, polypus removed_email_address@domain.invalid:

Did I miss something?

ok forget all of my above code. i’ve solved that problem in another
thread, see ‘mixin puzzle’.

but i would still like to know when one would prefer extending the
individual objects instead of ‘including’ into their class (and vice
versa), and what the pros and cons of each method are.

Well, the answe is pretty obvious: if you need all instances of a
class to have these methods you’ll certainly want to include the
module in the class. If you just want to modify individual objects
then you extend them on a one by one basis.

And I guess extending individual objects is less efficient (at least
memory wise) than doing it on the class level.

robert