Calling a dynamically generated Ruby script from a .rb

I have a Ruby script that dynamically generates a Ruby script. I would
like to execute the dynamically generated script from within my script.
I have some ideas but what’s the best way to do this? Got example code?
This has to work in a cross-platform environment (Windows, Linux, Mac)

Shouldn’t it just be as simple as picking a specific name, and then:

require name

?

M.T.

Or, maybe, in the generated file, have the main bit of code you want
to execute defined in a function, and call it after requiring it?

M.T.

Also, another option could be to call…

system “ruby #{name}”

(where name is a trusted name (including .rb) and isn’t potentially
dangerous user-input data).

Another option is to look at _Why the Lucky Stiff’s Sandbox (freaky
freaky snadbox, its endearing title) for something a bit more secure
for when you do need to deal with input from the user.

Hope this helps as well.

M.T.

On windows:

C:>echo class Fruit > module.rb
C:>echo def orange(taste) >> module.rb
C:>echo return "oranges tates " + taste.to_s >> module.rb
C:>echo end >> module.rb
C:>echo end >> module.rb
C:>irb
irb(main):002:0> load ‘module.rb’
=> true
irb(main):003:0> puts Fruit.new.orange(“sweet!”)
oranges tates sweet!
=> nil
irb(main):004:0>

Thanks but it doesn’t seem to work from a script. Just from irb:

% cat rtest.rb

#!/usr/bin/ruby -w

f = File.new(“newfile.rb”, “w+”)
f.puts(“class MyClass”)
f.puts(“def run()”)
f.puts(“print “hello world””)
f.puts(“end”)
f.puts(“end”)
load “newfile.rb”
MyClass.new.run()

% ./rtest
./rtest:10: uninitialized constant MyClass (NameError)

Robert La ferla wrote:

I have a Ruby script that dynamically generates a Ruby script. I would
like to execute the dynamically generated script from within my script.
I have some ideas but what’s the best way to do this? Got example code?
This has to work in a cross-platform environment (Windows, Linux, Mac)


Posted via http://www.ruby-forum.com/.

Why not just eval the generated code?

code = “class A; def to_s; “B”; end; end”
eval code
puts A.new.to_s

“R” == Robert La ferla [email protected] writes:

R> f = File.new(“newfile.rb”, “w+”)
R> f.puts(“class MyClass”)
R> f.puts(“def run()”)
R> f.puts(“print “hello world””)
R> f.puts(“end”)
R> f.puts(“end”)

f.close

R> load “newfile.rb”
R> MyClass.new.run()

Guy Decoux

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs