From: Logan Capaldo Date: 2007-05-21T22:28:56+09:00 Subject: Re: Dynamically creating ruby source files On 5/19/07, Matt Gretton wrote: > Hello all, > > What techniques do people generally use to create files and write ruby > code to them? > > One way of acheving this (a horrible way) would be just to write the > correct code to a file as follows. (This just creates a file called > file_test.rb that defines a module with two methods) > > > passed_in_name = "module1" > passed_in_methods = ["meth1","meth2"] > > File.open("test_file.rb","w") do |file| > file.puts "module #{passed_in_name}" > file.puts > > passed_in_methods.each do |meth| > file.puts "\tdef #{meth}" > file.puts "\t\t\#insert method code here" > file.puts "\tend" > file.puts > end > > file.puts "end" > end > > I feel there must exist a more elegant way of creating a file liek this. > For example, I have heard that ruby on rails dynamically creates files > containing ruby code. This behavior seems pretty common to various ruby > projects, for example I know rails creates ruby source code dynamically. > Not having had experience with such projects I have tried in vain to > search google for information. > > Any advice or generally a point the right direction (to other resources > etc) would be greatly appreciated. > I don't know that you necessarily want to create a file full of ruby source (you might) but alternatively you can use ruby's meta-programming facilities: passed_in_name = "Module1" passed_in_methods = ["meth1", "meth2"] mod = Module.new Object.const_set(passed_in_name, mod) mod.module_eval do passed_in_methods.each do |m| define_method(m) do |arg1, arg2, ..., argn| body_of_method end end end > Thanks in advance. > > Matt. > > -- > Posted via http://www.ruby-forum.com/. > >