Call Ruby shotgun executable from a Ruby script and open the browser to root URL

113 Views Asked by At

I am trying to call shotgun from a Ruby script. I want to both spin up the server and open the default browser (I'm on OS X Mavericks) to the root of the site. shotgun provides the --browse option for this, but I find it doesn't work, either from the Ruby script or from the terminal. Therefore I need to execute two commands from my script-- shotgun MYAPPFILE followed by open ROOTURL. The problem is that the shotgun MYAPPFILE command starts the shotgun process but does not exit, so open ROOTURL is never executed.

Also, I notice when I use backticks to call shotgun, none of the normal shotgun output is printed to STDOUT. But when I use system("shotgun MYAPPFILE"), I do see this output.

I want to start the server, open the browser to the root URL, and see the shotgun output. What is the best way to do this?

1

There are 1 best solutions below

0
On

This can be done with PTY (pseudo-terminal):

require 'pty'

PTY.spawn "shotgun app.rb" do |stdout, stdin, pid|
  begin
    trap('INT') { Process.kill("INT", pid) }
    `open http://localhost:9393`
    stdout.each { |li| puts li }
  rescue PTY::ChildExited
    puts "Shotgun exited!"
  end
end

The code above will exit when you hit Ctrl-c (i.e. send an interrupt). PTY is needed here as opposed to a normal process for reasons having to do with flushing of output. See this question for details.