Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add start and stop callbacks #1913

Merged
merged 10 commits into from
Jul 11, 2023
Next Next commit
Add start and stop callbacks
  • Loading branch information
jevin committed Jun 22, 2023
commit 73ed6d070534f0e79b2a5f7274e02c2597d2f166
15 changes: 13 additions & 2 deletions lib/sinatra/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,7 @@ class << self
%r{zeitwerk/kernel\.rb} # Zeitwerk kernel#require decorator
].freeze

attr_reader :routes, :filters, :templates, :errors
attr_reader :routes, :filters, :templates, :errors, :on_start_callback, :on_stop_callback

def callers_to_ignore
CALLERS_TO_IGNORE
Expand Down Expand Up @@ -1470,6 +1470,14 @@ def add_filter(type, path = /.*/, **options, &block)
filters[type] << compile!(type, path, block, **options)
end

def on_start(&on_start_callback)
@on_start_callback = on_start_callback
end

def on_stop(&on_stop_callback)
@on_stop_callback = on_stop_callback
end

# Add a route condition. The route is considered non-matching when the
# block returns false.
def condition(name = "#{caller.first[/`.*'/]} condition", &block)
Expand Down Expand Up @@ -1559,6 +1567,8 @@ def quit!
warn '== Sinatra has ended his set (crowd applauds)' unless suppress_messages?
set :running_server, nil
set :handler_name, nil

on_stop_callback.call
end

alias stop! quit!
Expand Down Expand Up @@ -1647,6 +1657,7 @@ def start_server(handler, server_settings, handler_name)
set :handler_name, handler_name
server.threaded = settings.threaded if server.respond_to? :threaded=

on_start_callback.call
yield server if block_given?
end
end
Expand Down Expand Up @@ -2037,7 +2048,7 @@ def self.delegate(*methods)
delegate :get, :patch, :put, :post, :delete, :head, :options, :link, :unlink,
:template, :layout, :before, :after, :error, :not_found, :configure,
:set, :mime_type, :enable, :disable, :use, :development?, :test?,
:production?, :helpers, :settings, :register
:production?, :helpers, :settings, :register, :on_start, :on_stop

class << self
attr_accessor :target
Expand Down