How does sinatra start the server?

亡梦爱人 提交于 2019-12-12 06:46:56

问题


I have been trying to delve into how sinatra works, and most recently I've been trying to figure out how sinatra starts the server after processing the routes, when it is required at the top of the file. I was looking at this tutorial and they end with an example app looking like this (their version of sinatra is called nancy):

# app.rb
# run with `ruby app.rb`
require "./nancy"

get "/" do
  "Hey there!"
end

Rack::Handler::WEBrick.run Nancy::Application, Port: 9292

I am wondering how you are not forced to include that last line in sinatra.


回答1:


Sinatra does that by defining an at_exit callback, see main.rb

This basically says "when the ruby script is done and exits, then run the Sinatra app!"

For more information see the ruby docs for at_exit!




回答2:


For serving a sinatra application you just need to execute ruby app.rb on shell.

app.rb

# install sinatra gem before everything 
# by typing `gem install sinatra`
# on shell. or add sinatra to your Gemfile
# then execute bundle install

require 'sinatra'

get '/' do 
  "Hey there"
end 

Then you'll see such output

$ ruby app.rb 
Puma 2.11.3 starting...
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:4567
== Sinatra (v1.4.7) has taken the stage on 4567 for development with backup from Puma

The tutorial you've been appealing at is not about the actual sinatra - there author have built his/her own pseudo-sinatra. By the way, ruby also have a microframework called nancy

To run his/her pseudo-sinatra successfully, you need to follow the tutorial from beggining to end.



来源:https://stackoverflow.com/questions/38357195/how-does-sinatra-start-the-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!