I have a very basic ruby example running on Thin, but I would like to know how to translate this example to use Unicorn or Puma as the HTTP server instead. Here is the code I have now:
require 'rack'
class HelloWorld
def talk()
return "Hello World!"
end
end
class SomeServer
def start(server_object, port)
app = proc do |env|
[ 200, {"Content-Type" => "text/html"}, [server_object.talk()] ]
end
Rack::Handler::Thin::run(app, :Port => port)
end
end
SomeServer.new.start(HelloWorld.new, 3000)
This runs fine and well, but I cannot figure out how to make it run using Puma or Unicorn instead. Most online documentation I find for the two is for Rails apps. How can I utilize the multi-threading capabilities of these servers with this simple program?
use sinatra.
So to take it step by step first install sinatra and puma gems
gem install sinatra
gem install puma
then create a file myapp.rb
require 'sinatra'
configure { set :server, :puma }
get '/' do
"Hello World!"
end
then run the file
ruby myapp.rb
by default sinatra listens on 4567 so go to localhost:4567 you can configure puma to listen on a specific port or do a lot of other things using a config file read the documentation
A minimal example that doesn't require additional gems looks like this.
Using a single file
Create a puma config file config.rb
with the following content:
app do |env|
body = 'Hello, World!'
[200, { 'Content-Type' => 'text/plain', 'Content-Length' => body.length.to_s }, [body]]
end
bind 'tcp://127.0.0.1:3000'
and run puma with
puma -C /path/to/config.rb
That's it.
Using a configuration and a rackup file
In the example above, the config file contains the application itself. It makes sense to move the application to a rackup file: Create a rackup file app.ru
with the following content:
class HelloWorld
def call(env)
body = 'Hello, World!'
[200, { 'Content-Type' => 'text/plain', 'Content-Length' => body.length.to_s }, [body]]
end
end
run HelloWorld.new
Then update your config.rb
, removing the app and linking the rackup file instead:
rackup '/path/to/app.ru'
bind 'tcp://127.0.0.1:3000'
and run puma as before with
puma -C /path/to/config.rb
The example configuration file for puma is helpful. (Update: This example configuration file is no longer maintained. The authors refer to dsl.rb instead.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With