Sinatra Application

I wish there was a template to create a sinatra application using a cli. But there isn’t a lot of boilerplate files to create, so lets add it one-by-one.

We’ll be using puma as the server. Create an app.rb file which defines a basic sinatra app with a / route. Also a Gemfile is added and bundle install is run.

require 'sinatra'
class ConferenceApp < Sinatra::Base
get '/' do
'It Works!'
end
end
view raw app.rb hosted with ❤ by GitHub

Next we need a rackup file config.ru so that puma will pickup the app as a rack application.

require './app'
run ConferenceApp
view raw config.ru hosted with ❤ by GitHub

Running the puma server will serve your application at http://localhost:9292, and you should see the message ‘It Works!’.

bundle exec puma

Yay! The app is up.

Add JSON responses

For the server to respond to JSON, we add the sinatra-contrib gem, which adds a JSON helper. Change the app.rb file to respond to json.

#file app.rb
require 'sinatra/json'
#...
get '/hello.json' do
message = { success: true, message: 'hello'}
json message
end
#...
view raw app_2.rb hosted with ❤ by GitHub

Now our app contains just these files:

conference_app
  |
  ├── Gemfile
  ├── Gemfile.lock
  ├── app.rb
  └── config.ru

Get notified on engineering articles like this

Follow us on twitter @neumeralhq