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/.
Shouldn't it just be as simple as picking a specific name, and then:
require name
?
M.T.
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
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:\>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>
···
On 7/28/06, Matt Todd <chiology@gmail.com> wrote:
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.
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)
···
--
Posted via http://www.ruby-forum.com/.