From: "David A. Black" Date: 2004-09-03T22:08:03+09:00 Subject: Re: [Design advice] including a file as code ('as is') Hi -- On Fri, 3 Sep 2004, Benny wrote: > dear list, > > I have 2 files: main.rb and include_me.rb. > I want include_me.rb to contain only the method definitions > (dont have to care about its module and class). > > [[background information: > the real problem is a bit more complicated. > finally 'main.rb' will open lots of different 'include_me.rb's in a loop > and even check if it has already opened them before open them twice, but > running classname.run each time in the loop (i.e. file name of the include > and classname are variables passed to main.rb in the loop)]] > > > the following code works, but > - will it always work no matter whats in 'include_me.rb'? > - is there a better solution to get rid of the evil "eval"? > > I know there is send(:define_method, "method_name") but I want > 'include_me.rb' to appear like if it would be a valid ruby script on its > own (without using any "special methods" only for the inclusion purpose). > > to simply redefine the same class in each include file is not an option. > > regards, > > benny > > ####### here comes the pseudo code ######### > > # main.rb > module My_Module > class MyTest > def initialize(str) > puts "initializing: #{str}" > end > lines = [] > File.open('include_me.rb').each_line{ |line | > lines << line > } > eval(lines.join(';')) I know you want to avoid eval, but as long as it's here, just to show you a somewhat shorter way to eval the contents of a file: eval(File.read("include_me.rb")) (Ruby really is good at doing things like that concisely :-) Anyway, as for another way: you could just 'require' the file, although then you end up with the methods being private. But if you know what they're called that may be not a big problem: module MyModule class MyTest def initialize(str) puts "initialize: #{str}" require "include_me.rb" self.class.class_eval { public :run } end end end etc. David -- David A. Black dblack@wobblini.net