Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Puma::Configuration to Sinatra?

Tags:

ruby

sinatra

puma

This is my web app:

class Front < Sinatra::Base
  configure do
    set :server, :puma
  end
  get '/' do
    'Hello, world!'
  end 
end

I start it like this (don't suggest to use Rack, please):

Front.start!

Here is my configuration object for Puma, which I don't know how to pass to it:

require 'puma/configuration'
Puma::Configuration.new({ log_requests: true, debug: true })

Seriously, how?

like image 933
yegor256 Avatar asked Oct 21 '18 16:10

yegor256


People also ask

How does PUMA work Ruby?

Puma processes requests using a C-optimized Ragel extension (inherited from Mongrel) that provides fast, accurate HTTP 1.1 protocol parsing in a portable way. Puma then serves the request using a thread pool.

What is PUMA gem?

Puma is a simple, fast, threaded, and highly concurrent HTTP 1.1 server for Ruby/Rack applications. Puma is intended for use in both development and production environments.

How do Pumas work?

Puma is a webserver that competes with Unicorn and allows you to handle concurrent requests. Puma uses threads, in addition to worker processes, to make more use of available CPU. You can only utilize threads in Puma if your entire code-base is thread safe.


2 Answers

Configuration is tightly connected to a way in which you run puma server.

The standard way to run puma - puma CLI command. In order to configure puma config file config/puma.rb or config/puma/<environment>.rb should be provided (see example).

But you asked how to pass Puma::Configuration object to puma. I wonder why you need it but AFAIK you need to run puma server programmatically in your application code with Puma::Launcher(see source code)

conf = Puma::Configuration.new do |user_config|
  user_config.threads 1, 10
  user_config.app do |env|
    [200, {}, ["hello world"]]
  end
 end
Puma::Launcher.new(conf, events: Puma::Events.stdio).run

user_config.app may be any callable object (compatible with Rack interface) like Sinatra application.

Hope it's helpful.

like image 174
andrykonchin Avatar answered Oct 13 '22 10:10

andrykonchin


Do you want to pass exactly an object or just a configuration in general? For the last option it's possible, but Puma will not log anything anyway (I'm not sure, but seems like you worry exactly about logging settings for Puma).

#!/usr/bin/env ruby

# frozen_string_literal: true

require 'bundler/inline'

gemfile(true) do
  gem 'sinatra'
  gem 'puma'
  gem 'openssl'
end

require 'sinatra/base'

class Front < Sinatra::Base
  configure do
    set :server, :puma
    set :server_settings, log_requests: true, debug: true, environment: 'foo'
  end

  get '/' do
    'Hello, world!'
  end
end

Front.start!
like image 35
Vasily Kolesnikov Avatar answered Oct 13 '22 09:10

Vasily Kolesnikov