4
require 'sinatra'
require 'rubygems'

class TestServer < Sinatra::Application
set :port, 22340
    get '/' do
        "Hello World"
    end
    run! if app_file == $0
end

Very Simple application with Ruby 2.0.0-p0 and Sinatra 1.4.2

When I ctrl-c the webrick server restarts on the default port... see output below

LM-BOS-00715009:server joshughes$ ruby test.rb 
[2013-04-19 16:07:48] INFO  WEBrick 1.3.1
[2013-04-19 16:07:48] INFO  ruby 2.0.0 (2013-02-24) [x86_64-darwin11.4.2]
== Sinatra/1.4.2 has taken the stage on 22340 for development with backup from WEBrick
[2013-04-19 16:07:48] INFO  WEBrick::HTTPServer#start: pid=63798 port=22340
^C
== Sinatra has ended his set (crowd applauds)
[2013-04-19 16:07:56] INFO  going to shutdown ...
[2013-04-19 16:07:56] INFO  WEBrick::HTTPServer#start done.
[2013-04-19 16:07:56] INFO  WEBrick 1.3.1
[2013-04-19 16:07:56] INFO  ruby 2.0.0 (2013-02-24) [x86_64-darwin11.4.2]
== Sinatra/1.4.2 has taken the stage on 4567 for development with backup from WEBrick
[2013-04-19 16:07:56] INFO  WEBrick::HTTPServer#start: pid=63798 port=4567
^C

Can anyone help me on what might be going wrong here?

matt
  • 78,533
  • 8
  • 163
  • 197
jjhughes57
  • 201
  • 3
  • 5

1 Answers1

6

The problem is you’re not correctly using the Sinatra modular style. Rather than requiring sinatra and inheriting from Sinatra::Application you should require sinatra/base and inherit from Sinatra::Base.

What’s happening is this. You require plain sinatra, which in turn requires sinatra/main. This file adds an at_exit handler that runs the built in server (unless you disable it). However you also explicitly call run! in your own code, so the server starts because of your call, then when you exit that the at_exit handler starts the server again. Requiring sinatra/base doesn’t start the built-in server at exit, so you’ll only have your own explicit call to run!.

require 'sinatra/base' # change here
require 'rubygems'

class TestServer < Sinatra::Base # and here
  set :port, 22340
  get '/' do
    "Hello World"
  end
  run! if app_file == $0
end
matt
  • 78,533
  • 8
  • 163
  • 197