Marnen Laibow-Koser wrote:
> James Byrne wrote:
>
> No. You'd be better off using require or similar.
>
That really depends upon the question being asked. The OP explicitly
asked on how to run an external script, that happened to be written in
Ruby; not, what is the best way to run arbitrary external ruby code from
inside a running Ruby script?
If the latter case then I suggest that the OP consider this approach,
which was recently shown to me by Matt Wynne on the Cucumber list:
First, write the script and encapsulate its entire code within an
execute method contained in a Script class file. Like so:
script.rb
class Script # should be the actual name of the script.
def initialize(argv) # receive the ARGV array from the calling
process
@argv = argv
end
def execute
# if required then parse any command line arguments in @argv here
puts "script.rb called"
end
end
#eof
If a stand-alone script initiation is required, as with cron say, then
write a stub script that calls the script class and executes the script
code like so:
runner.rb
#!/usr/bin/env ruby
require 'script'
Script.new(ARGV).execute
#eof
If the encapsulated script is complex enough that it contains its own
internal classes then the whole can be encapsulated inside an outer
class given the script name. The inner class containing the execute
method is then renamed to something like Main. In this case the call
becomes:
Script::Main.new(ARGV).execute
And the class file script.rb has this structure
class Script
class Main
def initialize(argv)
@argv = argv
end
def execute
script code goes here
end
end
class OtherClass
...
end
end
One may now use the script within any other ruby process as you suggest,
via a simple require and subsequent instantiation. I found this
technique extremely valuable in testing since out of process scripts did
not share the dbms state with the the test harness.
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---