razzi.abuissa.net

Razzi's guide to sinatra

Sinatra is a great Ruby web micro-framework.

Its docs are good! Here’s my minimal getting started guide.

Put this in app.rb:

require 'sinatra'

get '/' do
  'homepage'
end

Install the dependencies:

$ gem install --user-install sinatra rackup

Run the app:

$ ruby app.rb
[2024-12-29 23:54:24] INFO  WEBrick 1.8.1
[2024-12-29 23:54:24] INFO  ruby 3.2.3 (2024-01-18) [x86_64-linux-gnu]
== Sinatra (v4.1.1) has taken the stage on 4567 for development with backup from WEBrick
[2024-12-29 23:54:24] INFO  WEBrick::HTTPServer#start: pid=4104 port=4567

And it’s running on http://localhost:4567/ ! I’d have thought 5678 would have worked better with the music theme ;)

If you do actually want to change the port, add the following line:

set :port, 8000

live reloading

You’ll notice that if you edit the code, it isn’t applied to the currently running server.

The official docs at https://sinatrarb.com/faq.html#reloading recommend using an out-of-process approach (a rerun executable), but I’d prefer to be able to run the app without any prefix.

# I prefer:
$ ruby app.rb
# over:
$ rerun ruby app.rb

I like to use the in-process reloader which you can install like so:

$ gem install --user-install sinatra-contrib

Then you can enable live reloading like so:

require 'sinatra/reloader'

They say it’s deprecated but I hope they don’t take it away.

Other than requiring more typing, I found the rerun approach to be slower to reload.

templating

You’ll probably want to template a response. You can do it inline:

get '/' do
  template = "<%= 3 + 3 %>"
  erb template
end

But you’ll probably want to move it to its own file views/index.erb:

# app.rb:
get '/' do
  erb :index
end

# views/index.erb:
<%= 3 + 3 %>

To pass variables to the template, put them in a :locals hash:

get '/' do
  message = 'hi'
  erb :index, :locals => { message: }
end

# views/index.erb:
The message is <%= message %>

(this example is using the hash key-value punning syntax { message: })

Result:

$ curl localhost:8000
Message is: hi