From: "m4rkusha@..." Date: 2006-02-16T21:48:32+09:00 Subject: Re: Creating objects without knowing their names Robert Klemme wrote: > Joel VanderWerf wrote: > > paul.p.carey@gmail.com wrote: > >> Hi > >> > >> I'd like to load an arbitary number of Ruby files from a directory > >> and create their associated objects. However, I don't know the class > >> names of the files that have just been loaded. Is it possible to > >> determine a file's class name once that file has been loaded? > >> (Without resorting to parsing, or enforcing a mapping between the > >> filename and class name.) > > > You probably know this already, but for the benefit of bystanders: > > there isn't in general one-to-one mapping between classes and files. > > A class > > can be defined across several files; a file can contain several class > > definitions. (Maybe in the case of the files you are using there is > > always a 1-1 map, though.) > > There are other options. Some of them: > > - Make sure all classes on those files inherit a base class which > overrides #inherited so it gets notified every time a sub class is > created. You can then store the set of sub classes in a member of the > base class and use that for whatever purposes. > > - Make classes in those files register with some arbitrary registry you > create (that's basically the same as the first just more explicit). > > - use set_trace_func to trance execution of those files and notice > whenever a new class occurs. (Not sure whether that works though). > > Kind regards > > robert Or you can compare the classes you had before loading to classes you had after loading. Something like this: def defined_classes classes = [] ObjectSpace.each_object(Class){|c| classes << c} classes end initial_classes = defined_classes require 'net/http' p defined_classes - initial_classes