Calling a dynamically generated Ruby script from a .rb

R

Robert La ferla

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)
 
M

Matt Todd

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

require name

?

M.T.
 
M

Matt Todd

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.
 
M

Matt Todd

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.
 
X

x1

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>
 
R

Robert La ferla

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)
 
T

ts

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
 
T

Timothy Goddard

Robert said:
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)

Why not just eval the generated code?

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,209
Messages
2,571,088
Members
47,686
Latest member
scamivo

Latest Threads

Top