Keith Bennett
Keith Bennett

Reputation: 4970

Can I stop Sinatra from within a Sinatra application?

I'd like to know how to programmatically exit a Sinatra application from within the application itself. (There's another SO thread about stopping it from outside the app.)

I want to use Sinatra as a means of receiving control and configuration commands while my application does something unrelated to the Sinatra stuff. I'd like one of the control commands to be 'exit'. Ruby's 'exit' method just seems to result in Sinatra recovering and resuming. I found this in base.rb that I think confirms this:

at_exit { Application.run! if $!.nil? && Application.run? }

So far, the only way I've found is to call Ruby's exit! method, but that bypasses exit hooks and is not a very clean solution.

Is there no way to programmatically tell Sinatra to stop?

Upvotes: 3

Views: 1837

Answers (4)

igneus
igneus

Reputation: 1012

Sinatra::Base::quit! or its alias ::stop! is what you are looking for:

require 'sinatra'

get '/quit' do
  self.class.quit!
end

get '/stop' do
  self.class.stop!
end

Upvotes: 1

Jon Cairns
Jon Cairns

Reputation: 11949

Why not just raise an exception? That will mean that $! is not nil, so the at_exit handler won't restart Sinatra.

An easy way is just to run fail or raise. You can also pass a message, such as fail "Exiting due to x".

Upvotes: 1

sashaegorov
sashaegorov

Reputation: 1862

I used the following code:

# Exit 'correctly'
get '/exit' do
  # /exit causes:
  # 15:20:24 web.1  | Damn!
  # 15:20:24 web.1  | exited with code 1
  Process.kill('TERM', Process.pid)
end

# Just terminate
get '/fail' do
  Process.kill('KILL', Process.pid)
end

Take a look at at_exit in config.ru it works for TERM signal:

at_exit do
  puts 'Damn!'
  exit false
end

Full example is here.

Cheers.

Upvotes: 3

bigtunacan
bigtunacan

Reputation: 4996

That sort of goes against the grain of Sinatra, but this is just Ruby so you can easily do this via open classes/monkey patching.

Just re-open the base.rb at_exit method and override the Application.run! behavior.

Upvotes: 1

Related Questions