Skip to content

Instantly share code, notes, and snippets.

@asaaki
Last active February 25, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaaki/44ad747304e3fd365f5d4f0a242784b6 to your computer and use it in GitHub Desktop.
Save asaaki/44ad747304e3fd365f5d4f0a242784b6 to your computer and use it in GitHub Desktop.

Minimal Test for Sinatra: single global vs each request

Setup to show the difference between the different ways of using set in Sinatra::App.

Run it

bundle exec puma -C ./puma.rb

And then make some calls from another shell:

# test single
ab -n 10 -c 1 http://127.0.0.1:3333/one

# test each
ab -n 10 -c 1 http://127.0.0.1:3333/each
# frozen_string_literal: true
require 'logger'
require 'sinatra/base'
require 'sinatra/json'
class SomeSingleton
MSG = 'I got called.'
def initialize(logger)
@logger = logger
logger.info("==> Instance created! <==")
end
def call
@logger.info("--> #{MSG}")
MSG
end
end
class App < Sinatra::Base
set :log_device, STDOUT
set :logger, -> { Logger.new(settings.log_device) }
set :show_exceptions, false
set :raise_errors, false
set :dump_errors, false
set :globally_one, SomeSingleton.new(logger)
set :each_request, -> { SomeSingleton.new(logger) }
before { content_type('application/json') }
get('/one') { [200, json(Hash.new(msg: settings.globally_one.call))] }
get('/each') { [200, json(Hash.new(msg: settings.each_request.call))] }
end
# frozen_string_literal: true
require './app'
run App
# frozen_string_literal: true
source 'https://rubygems.org'
gem 'puma'
gem 'sinatra'
gem 'sinatra-contrib'
# frozen_string_literal: true
environment ENV['RACK_ENV'] || 'development'
workers 0 # no workers, just threads!
threads 2, 2
bind 'tcp://0.0.0.0:3333'
preload_app!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment