From: dblack@... Date: 2006-04-11T11:12:36+09:00 Subject: Re: Identfying classes in a file dynamically Hi -- On Tue, 11 Apr 2006, Joel VanderWerf wrote: > Navya Amerineni wrote: >> Hi, >> >> I was trying to identify the classes in a give file at the run time. the following is the code i used. >> sc, ec = [], [] >> ObjectSpace.each_object(Class) { |c| sc << c } >> require 'Roman.rb' >> ObjectSpace.each_object(Class) { |c| ec << c } >> new_classes = ec - sc >> puts new_classes >> sc, ec = [], [] >> ObjectSpace.each_object(Class) { |c| sc << c } >> require 'Roman1.rb' >> ObjectSpace.each_object(Class) { |c| ec << c } >> new_classes = ec - sc >> puts new_classes >> >> Both roman.rb and roman1.rb has the same class Roman. >> the first time i print the new_classes i can see the Roman class in the output but the second one does not print because the class Roman is arleady read previously. >> >> is there a way i can over come this problem and identify the Roman class twice. > > One way is to wrap the file in a module, so that the constants defined > in it will not collide with other constants. > > file = "some/file" > m = Module.new > m.module_eval(IO.read(file), File.expand_path(file)) > p m.constants > > But then the Roman module won't be available except as m::Roman. To fix > this, you could include m into any class or module that needs to use Roman. Also I think that if the read-in file uses the ::Const construct, those classes won't get counted. David -- David A. Black (dblack@wobblini.net) Ruby Power and Light, LLC (http://www.rubypowerandlight.com) "Ruby for Rails" coming in PDF April 15, and in paper May 5! http://www.manning.com/black