Table of Contents
Last updated
January 9, 2019
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra' | |
class ConferenceApp < Sinatra::Base | |
get '/' do | |
'It Works!' | |
end | |
end |
Next we need a rackup file config.ru so that puma will pickup the app as a rack application.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require './app' | |
run ConferenceApp |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#file app.rb | |
require 'sinatra/json' | |
#... | |
get '/hello.json' do | |
message = { success: true, message: 'hello'} | |
json message | |
end | |
#... |
Now our app contains just these files:
conference_app
|
├── Gemfile
├── Gemfile.lock
├── app.rb
└── config.ru
…