From: "David A. Black" Date: 2005-05-17T20:34:29+09:00 Subject: Re: Extending an Instance only Once HI -- On Tue, 17 May 2005, Gavin Kistner wrote: > I have a method that requires that the arguments passed to it have been > in-mixed with a module. Currently, my code looks like this: > > def my_method( the_obj ) > the_obj.extend( MyModule ) unless the_obj.inherits_from?( MyModule ) > end > > class Object > def selfclass > class << self; self; end > end > > # Return true if the instance inherits from the supplied > _class_or_module_. > def inherits_from?( class_or_module ) > self.class.ancestors.include?( class_or_module ) or > self.selfclass.ancestors.include?( class_or_module ) > end > end > > > Is there a better way to do that? Unless I'm missing something, #is_a? would do it. > (I'm testing if the object inherits from a > class which was extended by the module, OR if the instance itself was already > extended.) Does it end up being cheaper/faster to just always re-extend the > instance? (What happens if you extend both the class and an instance of that > class? Does the singleton class take precedence?) The singleton class takes precedence in the sense that it comes earlier in the method lookup path. (I'm assuming that you mean mixing the module into the class, not MyClass.extend(MyMod), which would not affect the class's instances.) Overall, I'm tempted to say that if you're extending a single object multiple times with the same module, there's something not quite right in the program flow. But I doubt it's going to slow things down very much (but I haven't benchmarked it). David -- David A. Black dblack@wobblini.net