From: Sam Hendley Date: 2008-08-21T23:26:57+09:00 Subject: Re: Alternatives to class variables Pit Capitain wrote: > 2008/8/20 Sam Hendley : >> Hello, this is my first post to this list and I have only been using >> ruby for a couple of weeks so forgive me if its overly simple, I spent a >> few hours searching and wasn't able to figure this out myself. > > Welcome Sam. Before answering, let me ask you two more questions :-) > > 1) Why are you asking the instances about the extra methods? Instead of > > Foo.new.extra_methods > > I would expect > > Foo.extra_methods > > Or do you want to define extra methods for individual objects, too? > > 2) How deep will your class hierarchy be? What about subclasses of > Foo, for example, after > > class SubFoo < Foo > add_method :foo_4 > end > > what should be the result of > > SubFoo.new.extra_methods.size > > BTW: the normal indentation of Ruby code is with two spaces per level. > > Regards, > Pit Thanks for the response. 1) I am asking the individual instances for their "extra_methods" because I am creating collections of these objects that higher level objects that use the meta-data I collect during the method declaration to do some cool things. I hadn't thought of doing something like instance.class.new.extra_methods but I'm not sure if it would work (without being just as ugly as it is now) because of the class variable inheritance rules. 2) the class hierarchy won't be any deeper than one level (Base + SubClass). I'm open to anything at this point, it occured to me that I could just store all of the extra information directly in another object (better the base class?) using a hash on the subclass type. The objects themselves don't need to use meta-data I'm collecting. < snip 5 minutes > Well your questions got me started down the right road and I have a solution that solves my immediate problem (though I am still interested in the "right way" that keeps the infomration with the classes themselves). I used a class level hash on the base class that looks up the extra methods based on self.class on a call. I applied this to my "real world" problem as well and it worked perfectly, should have thought of this earlier, but I got fixated on keeping all the information in the classes themselves. For completeness sake and if someone finds this on google here is my solution: module MethodCollector def self.included( klass) klass.extend ClassMethods end module ClassMethods def addpoint(name) MethodAdderBase.extra_methods[self] ||= [] MethodAdderBase.extra_methods[self] << name end def add_method(name) method_name = (name.to_s).to_sym self.send :define_method, method_name do "MethodName is: #{method_name}" end addpoint(name) end end end class MethodAdderBase include MethodCollector @@extra_methods = {} def self.extra_methods @@extra_methods end def extra_methods @@extra_methods[self.class] end end -- Posted via http://www.ruby-forum.com/.